PHP 操作数据库的方式有多种如 mysql
、mysqli
、PDO
,目前主要使用的是 PDO 处理。
MySQLi或PDO扩展来操作MySQL数据库。这两个扩展提供了一组函数和方法,用于连接到数据库、执行查询、插入、更新和删除数据等操作。
PDO 提供了一个数据访问抽象层,不管使用哪种数据库,都可以用相同的函数(方法)来查询和获取数据。
// 数据库连接配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
// 创建数据库连接
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// 设置错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 执行查询
$sql = "SELECT * FROM your_table";
$stmt = $conn->query($sql);
// 处理查询结果
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo "ID: " . $row['id'] . ", Name: " . $row['name'] . "
";
}
} catch (PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 关闭数据库连接
$conn = null;
PDO的错误处理
错误类型 | 说明 |
---|---|
PDO::ERRMODE_SILENT | 不显示错误 |
PDO::ERRMODE_WARNING | 显示警告错误 |
PDO::ERRMODE_EXCEPTION | 抛出异常 |
MySQLi扩展连接到MySQL数据库,并执行查询操作:
// 数据库连接配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $database);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 执行查询
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
// 处理查询结果
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . "
";
}
} else {
echo "没有结果";
}
// 关闭数据库连接
$conn->close();
常见的MySQLi错误类型:
mysqli_connect_errno()
:返回连接错误的错误代码。mysqli_connect_error()
:返回连接错误的错误消息。mysqli_errno($conn)
:返回最近一次查询错误的错误代码。mysqli_error($conn)
:返回最近一次查询错误的错误消息。mysqli_sqlstate($conn)
:返回最近一次查询的SQL状态码,用于识别语法错误等。mysqli_stmt_errno($stmt)
:返回预处理语句错误的错误代码。mysqli_stmt_error($stmt)
:返回预处理语句错误的错误消息。下面是PDO的常用函数:
连接时设置错误类型
$pdo = new PDO($dns, $config['user'], $config['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
使用 setAttribute
方法设置错误处理方式
$pdo = new PDO($dns, $config['user'], $config['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
exec执行SQL
$pdo->exec("INSERT INTO news (title) VALUES('php_project')");
echo "自增主键:".$pdo->lastInsertId();
$affectedRows = $pdo->exec("DELETE FROM news WHERE id>3");
echo "受影响的条数:".$affectedRows;
fetchAll 一次获取所有结果
...
$query = $pdo->query("select * from goods");
$rows = $query->fetchAll();
print_r($rows);
...
fetch 每次获取结果中的一条数据
...
$pdo = new PDO($dns, $config['user'], $config['password']);
$query = $pdo->query("select * from goods");
while ($field = $query->fetch(PDO::FETCH_ASSOC)) {
echo sprintf("编号:%s\t名称:%s
", $field['id'], $field['title']);
}
SQL 注入
$query = $pdo->query("SELECT * FROM news WHERE id={$_GET['id']}");
如果 GET 参数如下将产生 SQL 注入
http://ss-s.cc/test/1.php?id=1 or id>1
使用预准备
下面使用参数绑定来执行预准备的查询操作
$sql = "SELECT * FROM news WHERE id=:id";
$sth = $pdo->prepare($sql);
$sth->execute(['id' => $_GET['id']]);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($rows);
下面使用参数绑定形式的预准备操作执行添加操作
$sql = "INSERT INTO news (title) VALUES(:title)";
$sth = $pdo->prepare($sql);
$sth->execute(['title'=>'ss-s.cc']);
echo $pdo->lastInsertId();
占位符
使用问号占位符是另一种使用预准备的方式
$sth = $pdo->prepare("SELECT * FROM news WHERE id>?");
$sth->execute([3]);
print_r($sth->fetchAll());
使用占位符来执行添加操作
$sql = "INSERT INTO news (title) VALUES(?)";
$sth = $pdo->prepare($sql);
$sth->execute(['ss-s.cc']);
echo $pdo->lastInsertId();
以下是封装好链式调用的一个类:
class QueryBuilder
{
protected $pdo;
protected $table;
protected $select = '*';
protected $where = '';
protected $groupBy = '';
protected $orderBy = '';
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function table($table)
{
$this->table = $table;
return $this;
}
public function select($columns)
{
$this->select = $columns;
return $this;
}
public function where($condition)
{
$this->where = "WHERE $condition";
return $this;
}
public function groupBy($column)
{
$this->groupBy = "GROUP BY $column";
return $this;
}
public function orderBy($column, $direction = 'ASC')
{
$this->orderBy = "ORDER BY $column $direction";
return $this;
}
public function get()
{
$sql = "SELECT {$this->select} FROM {$this->table} {$this->where} {$this->groupBy} {$this->orderBy}";
$stmt = $this->pdo->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
// 使用示例
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = new QueryBuilder($pdo);
$result = $query->table('your_table')
->select('id, name, email')
->where('age > 18')
->groupBy('gender')
->orderBy('name', 'ASC')
->get();
foreach ($result as $row) {
echo "ID: " . $row['id'] . ", Name: " . $row['name'] . ", Email: " . $row['email'] . "
";
}
} catch (PDOException $e) {
echo "错误: " . $e->getMessage();
}
请点赞,收藏,关注!感谢!