php - SELECT COUNT(*) 是否适用于 MySQLi 准备好的语句?

标签 php mysqli prepared-statement

我正在处理一个测试页面,在阅读它们使我的代码免受 SQL 注入(inject)攻击后,我在我的查询中使用了 MySQLi 准备好的语句。到目前为止,我已经成功地使用准备好的语句从我的数据库中检索数据,一切都很好。

我现在想做的是使用 SELECT COUNT(*) 计算项目中画廊的数量。就是这样。

在不使用准备好的语句的情况下,我的旧查询如下所示:

// count number of galleries per project
$conn = dbConnect('query');
$galNumb = "SELECT COUNT(*) FROM pj_galleries WHERE project = {$pjInfo['pj_id']}";
$gNumb = $conn->query($galNumb);
$row = $gNumb->fetch_row();
$galTotal = $row[0];

但是通过我所有的阅读和搜索互联网,我找不到将其写成准备好的陈述的正确方法。

最佳答案

是的,它应该工作得很好。

但是,请记住执行 COUNT(primary_key) 通常会提供更好的性能。

所以你上面的查询看起来像

// first, setup your DB-connection
$mysqli = new mysqli('example.com', 'user', '********', 'database');

// Preparing the statement
$stmt = $mysqli->prepare('SELECT COUNT(*) FROM pj_galleries WHERE project = ?');

// binding the parameters
$stmt->bind_param('i', $pjInfo['pj_id']); // 'i' signals an integer

// Executing the query
if ( ! $stmt->execute()) {
    trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
}

// fetching the results
$col1 = null;
$stmt->bind_result($col1); // you can bind multiple colums in one function call
while ($stmt->fetch()) { // for this query, there will only be one row, but it makes for a more complete example
    echo "counted {$col1} records\n";
}

$stmt->close(); // explicitly closing your statements is good practice

为了更好更完整的解释,请看:http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php (示例应该能让您快速上手)。

另请记住,如果需要,您可以多次执行准备好的语句。您还可以在重新执行查询之前绑定(bind)新参数。

关于php - SELECT COUNT(*) 是否适用于 MySQLi 准备好的语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713512/

相关文章:

php - 如何处理删除 JSON :API? 中的关系

php - 从 MYSQL 更新到 MYSQLI

php - 使用准备好的声明无法清理表单

php - 本例中如何将 mysql_result 转换为 mysqli 结果

postgresql - 作为查询的存储过程 : CallableStatement vs. PreparedStatement

php - 连接到 Mysql 数据库的操作有多昂贵?

php - Grocery CRUD ajax 性能

python - Python 是否支持 MySQL 准备好的语句?

php - 判断一个字符是否是字母

php - MySQLi 绑定(bind)结果并获取多行