PHP操作MySQL
在Web开发中,PHP和MySQL是一对常见的组合,PHP是一种服务器端的脚本语言,而MySQL则是一种关系型数据库管理系统,通过PHP操作MySQL,可以实现动态网站的开发,本文将介绍如何使用PHP来操作MySQL数据库。
连接MySQL数据库
要使用PHP操作MySQL,首先需要连接到MySQL数据库,可以使用mysqli扩展或者PDO扩展来实现。
1、使用mysqli扩展连接MySQL
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn>connect_error) { die("连接失败: " . $conn>connect_error); } echo "连接成功"; ?>
2、使用PDO扩展连接MySQL
<?php $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语句了,可以使用mysqli或PDO的API来执行SQL语句。
1、使用mysqli执行SQL语句
<?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 结果"; } $conn>close(); ?>
2、使用PDO执行SQL语句
<?php $sql = "SELECT id, firstname, lastname FROM MyGuests"; foreach ($conn>query($sql) as $row) { echo $row['id'] . "t" . $row['firstname'] . "t" . $row['lastname'] . "<br>"; } $conn = null; ?>
插入、更新和删除数据
除了查询数据外,还可以使用PHP操作MySQL进行插入、更新和删除数据的操作。
1、插入数据
<?php $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; } $conn>close(); ?>
2、更新数据
<?php $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if ($conn>query($sql) === TRUE) { echo "记录更新成功"; } else { echo "Error updating record: " . $conn>error; } $conn>close(); ?>
3、删除数据
<?php $sql = "DELETE FROM MyGuests WHERE id=1"; if ($conn>query($sql) === TRUE) { echo "记录删除成功"; } else { echo "Error deleting record: " . $conn>error; } $conn>close(); ?>
预处理语句
为了提高安全性和性能,可以使用预处理语句,预处理语句可以防止SQL注入攻击,并且可以提高数据库性能。
1、使用mysqli预处理语句
<?php $stmt = $conn>prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt>bind_param("sss", $firstname, $lastname, $email); $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt>execute(); echo "新记录插入成功"; $stmt>close(); $conn>close(); ?>
2、使用PDO预处理语句
<?php $stmt = $conn>prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"); $stmt>bindParam(':firstname', $firstname); $stmt>bindParam(':lastname', $lastname); $stmt>bindParam(':email', $email); $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt>execute(); echo "新记录插入成功"; $conn = null; ?>
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/769990.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复