赣南脐橙

keybr

佰草伐

导航

PHP 连接MySQL

连接MySQL

在我们访问MySQL数据库前,我们需要先连接到数据库服务器:

实例(MySQLi - 面向对象)

 

<?php
$servername = "localhost";
$username = "username";
$password = "password";
 
// 创建连接
$conn = new mysqli($servername, $username, $password);
 
// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
} 
echo "连接成功";
?>

 

实例(PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
 
try {
    $conn = new PDO("mysql:host=$servername;", $username, $password);
    echo "连接成功"; 
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
?>

 

关闭连接:

 

实例(MySQLi - 面向对象)

$conn->close();

实例(PDO)

$ conn = null;

 

posted on 2019-07-09 15:50  佰草伐  阅读(1992)  评论(1编辑  收藏  举报

keybr

php基础知识

Wood Furniture