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

PHP implements MySQL database connection

Guanhui
GuanhuiOriginal
2020-05-06 14:26:017086browse

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('数据库连接失败!');

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()); 

}

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();

}

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();

}

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!

Statement:
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