PHP

php后台框架的数据库连接方式

小樊
84
2024-07-15 14:52:45
栏目: 编程语言

PHP后台框架通常使用PDO(PHP Data Objects)或者MySQLi(MySQL Improved)这两种方式来连接数据库。

  1. PDO连接方式:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
  1. MySQLi连接方式:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

这两种连接方式都可以用来连接MySQL数据库,但PDO更加灵活和方便,支持多种数据库类型,而MySQLi只支持MySQL数据库。在实际开发中,可以根据具体需求来选择适合自己项目的数据库连接方式。

0
看了该问题的人还看了