Home > Backend Development > PHP Problem > PHP implements MySQL database connection

PHP implements MySQL database connection

Guanhui
Release: 2023-02-28 22:12:02
Original
7138 people have browsed it

PHP implements MySQL database connection
php implements MySQL database connection

1. Connect through the "mysql_connect()" function;

$mysql_server='localhost';
$mysql_username='用户名';
$mysql_password='用户密码';
$mysql_database='数据库名';//建立数据库连接
$conn=mysql_connect($mysql_server,$mysql_username,$mysql_password) or die('数据库连接失败!');
Copy after login

2. Use "mysqli_connect ()" or "new mysqli()" to connect, these two methods are the same, just different styles;

The first method is process-oriented

$mysql_server_name = 'localhost'; //改成自己的mysql数据库服务器

$mysql_username = 'root'; //改成自己的mysql数据库用户名

$mysql_password = 'password'; //改成自己的mysql数据库密码

$mysql_database = 'test'; //改成自己的mysql数据库名

$conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库

//连接数据库错误提示

if (mysqli_connect_errno($conn)) { 

    die("连接 MySQL 失败: " . mysqli_connect_error()); 

}
Copy after login

The second method Object-oriented

//连接数据库方式1

$conn = new mysqli('localhost', 'root', 'password', 'test');

//连接数据库方式2

// $conn = new mysqli();

// $conn -> connect('localhost', 'root', 'password', 'test');

//check connection (检查PHP是否连接上MYSQL)

if ($conn -> connect_errno) {

    printf("Connect failed: %s\n", $conn->connect_error);

    exit();

}
Copy after login

3. Connect based on PDO.

$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'password');

try {

    foreach ($db->query('select * from db_table') as $row){

    print_r($row);

    }

    $db = null; //关闭数据库

} catch (PDOException $e) {

    echo $e->getMessage();

}
Copy after login

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of PHP implements MySQL database connection. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template