在本教程中,我们将学习如何使用PDO语句对象从表中以不同的查询模式进行数据查询。
为了从数据库表中查询数据,您必须执行以下步骤:
此query()方法返回一个PDO 语句对象,该对象允许您遍历返回的结果集。如果在执行SQL语句期间发生错误,则query()方法返回false。
例如,如果您想要查询employees数据库(empdb)中的departments表的所有数据,您可以使用以下脚本:
<?php
require_once
'dbconfig.php'
;
// MySQL DSN
$dsn
=
"mysql:host=$host;dbname=$db"
// 获取所有的部门
$sql_get_depts
"SELECT * FROM departments"
try
{
$dbh
new
PDO(
,
$username
$password
);
$stmt
->query(
if
(
=== false) {
die
"Error executing the query: $sql_get_depts"
}
catch
(PDOException
$e
) {
echo
->getMessage();
?>
<!DOCTYPE html>
<html>
<head>
<title>Departments</title>
<link rel=
"stylesheet"
href=
"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css"
>
</head>
<body>
<h1>Departments</h1>
<table
class
"table table-striped table-bordered"
style=
"width:300px;"
<thead>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody>
while
$row
->fetch(PDO::FETCH_ASSOC)) : ?>
<td><?php
htmlspecialchars(
[
'department_no'
]); ?></td>
'name'
endwhile
; ?>
</tbody>
</table>
</body>
</html>
当我们使用PDO::FETCH_ASSOC fetch模式时,PDOStatement将返回一个按列名索引的数组。
PDO提供了好几种获取模式。我们将讨论最常用的。
如果您没有将获取模式传递给fetch()方法,它将使用默认的获取模式,即PDO::FETCH_BOTH,它指示fetch()方法返回一个按列名和整数索引的数组。
例如,如果您使用PDO::FETCH_BOTH获取模式,您可以通过以下方式访问department列:
]
也可以这样获取
[0]
模式PDO::FETCH_NUM允许fetch()方法返回一个按整数索引的数组。
因此,PDO::FETCH_BOTH模式等同于同时设置PDO::FETCH_ASSOC和PDO::FETCH_NUM模式。
在调用fetch()方法之前,可以通过调用PDOStatement对象的setFetchMode()方法来设置读取模式。
请看下面的示例:
->setFetchMode(PDO::FETCH_BOTH);
$r
->fetch()){
//..
PDO语句允许您进行多次查询,但是在查询新的结果集之前,您必须调用closeCursor()方法。
下面的示例显示了编号为1的部门并且属于该部门的员工。
// 获取编号为1的部门
= "SELECT * FROM departments
WHERE department_no = 1";
<link href=
"css/bootstrap.min.css"
rel=
->closeCursor();
// 获取属于部门1的员工
$sql_get_emps_by_dept
= "SELECT * FROM employees
WHERE department_no = 1
ORDER BY last_name";
"执行查询时出错: $sql_get_emps_by_dept"
<h2>Employees</h2>
"width:600px;"
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Birth
Date
</th>
<th>Hire
'employee_no'
'last_name'
'first_name'
'gender'
'birth_date'
'hire_date'
原文链接:https://codingdict.com/