📅  最后修改于: 2023-12-03 15:06:48.825000             🧑  作者: Mango
PHP是一种广泛使用的脚本语言,它可以轻松地与各种数据库协作。在PHP中,我们可以使用两种主要的方式进行数据库操作,即mysqli和pdo。
无论是使用mysqli还是pdo,都需要连接到数据库,执行SQL语句,然后对返回结果进行处理。本文将介绍如何使用这两种方式以及它们的区别和优缺点。
连接到MySQL数据库的例子:
<?php
$server = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($server, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
下面是使用mysqli执行SELECT语句的例子:
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
连接到MySQL数据库的例子:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
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();
}
?>
下面是使用PDO执行SELECT语句的例子:
<?php
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
$conn = null;
?>
两种方式都很强大,但是同时也有自己的优缺点。Mysqli有更好的执行能力和事务处理,而PDO则更容易学习和更具有灵活性以连接多个不同类型的数据库。也就是说,如果你开发的是只针对Mysql的项目,那么你应该选择mysqli来进行开发,但如果你需要连接多种类型的数据库,那么你应该选择使用PDO。
// 使用 mysqli 连接到数据库
$server = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($server, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// 使用 mysqli 执行 SELECT 语句
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
// 使用 PDO 连接到数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
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();
}
// 使用 PDO 执行 SELECT 语句
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
$conn = null;