PHP数据库操作详解
我们将详细介绍PHP与数据库的交互过程,包括连接数据库、执行SQL语句、处理结果集以及关闭数据库连接等,我们将重点介绍PHP中的PDO(PHP Data Objects)和MySQLi扩展两种常用的数据库操作方式。
1、PHP数据库连接
要使用PHP进行数据库操作,首先需要建立与数据库的连接,以下是使用PDO和MySQLi扩展分别建立连接的方法:
(1)使用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 "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> ```</pre><p>(2)使用MySQLi连接MySQL数据库</p><pre class="brush:php;toolbar:false"><?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 "Connected successfully";
?>
```</pre><p>2、SQL语句执行与结果处理</p><p>(1)使用PDO执行SQL语句并获取结果集</p><pre class="brush:php;toolbar:false">
<?php try { $sql = "SELECT id, name FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>"; } } else { echo "0 结果"; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; ?> ```</pre><p>(2)使用MySQLi执行SQL语句并获取结果集</p><pre class="brush:php;toolbar:false"><?php
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出每行数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>"; } } else { echo "0 结果";} ?> ``` </pre>
还没有评论,来说两句吧...