如何有效地使用PHP操作MySQL数据库?

PHP操作MySQL数据库

PHP可以通过MySQLi或PDO扩展来操作MySQL数据库,以下是使用MySQLi和PDO的示例代码:

如何有效地使用PHP操作MySQL数据库?插图1
(图片来源网络,侵删)

1. MySQLi

连接数据库

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

执行SQL查询

$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 结果";
}

插入数据

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
    echo "新记录插入成功";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

关闭连接

如何有效地使用PHP操作MySQL数据库?插图3
(图片来源网络,侵删)
$conn->close();

2. PDO

连接数据库

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "连接成功"; 
} catch(PDOException $e) {
    echo "连接失败: " . $e->getMessage();
}

执行SQL查询

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$stmt = $conn->prepare($sql);
$stmt->execute();
// 设置结果集为关联数组
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
    echo "id: " . $v['id'] . " Name: " . $v['firstname'] . " " . $v['lastname'] . "<br>";
}

插入数据

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)";
$stmt= $conn->prepare($sql);
$stmt->execute(['John', 'Doe', 'john@example.com']);
echo "新记录插入成功";

关闭连接

如何有效地使用PHP操作MySQL数据库?插图5
(图片来源网络,侵删)
$conn = null;

本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/57795.html

小末小末
上一篇 2024年9月24日 11:22
下一篇 2024年9月24日 11:38

相关推荐