【发布时间】:2021-01-08 18:03:08
【问题描述】:
我正在关注this tutorial,在 PDO 中进行动态 WHERE 子句查询。
假设我有一个简短的教程代码,就像这样:
// always initialize a variable before use!
$conditions = [];
$parameters = [];
// conditional statements
if (!empty($_GET['name']))
{
// here we are using LIKE with wildcard search
// use it ONLY if really need it
$conditions[] = 'name LIKE ?';
$parameters[] = '%'.$_GET['name']."%";
}
if (!empty($_GET['sex']))
{
// here we are using equality
$conditions[] = 'sex = ?';
$parameters[] = $_GET['sex'];
}
// the main query
$sql = "SELECT * FROM users";
// a smart code to add all conditions, if any
if ($conditions)
{
$sql .= " WHERE ".implode(" AND ", $conditions);
}
// the usual prepare/execute/fetch routine
$stmt = $pdo->prepare($sql);
$stmt->execute($parameters);
$data = $stmt->fetchAll();
通过添加行$count = $stmt->rowCount();,我可以计算行数。
现在假设我有这样的数据:
| ID | User name | sex |
| -- | ------------ | --------|
| 1 | Sandra Smith | female |
| 2 | Ben Smith | male |
| 3 | John Lee | male |
| 4 | John Smith | male |
如果我现在搜索“Smith”,我会得到 3 个结果,当我回显 $count 时,会显示数字 3。
问题: 我还想回应我通过完全相同的查询获得了多少女性和男性用户。 我在互联网上进行了很多搜索,但找不到使用 PDO 解决此问题的案例。另外,我不确定是否需要另一个额外的查询来获取女性和男性用户的数量。
【问题讨论】: