PHP7连接MySQL数据库有两种方法

| |
[不指定 2021/04/09 10:57 | by admin ]
MySQLi连接

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// 创建连接
$conn = new mysqli($servername, $username, $password);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
echo "连接成功";

$conn->close(); //关闭连接


PDO连接

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

$conn = null; //关闭连接
}
PHP笔记 | 评论(0) | 引用(0) | 阅读(175)