10

我正在一个测试页面上工作,并且在阅读后在我的查询中使用 MySQLi 准备好的语句,它们使我的代码免受 SQL 注入的影响。到目前为止,我已经成功地使用准备好的语句从我的数据库中检索数据,这一切都很好。

我现在要做的是使用 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];

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

4

2 回答 2

16

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

但是,请记住,执行 aCOUNT(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 (示例应该让您加快速度)。

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

于 2012-12-04T23:02:12.163 回答
9

你可能想多了,因为它与任何其他准备好的语句没有什么不同:

$conn = new mysqli;
$sql = "SELECT COUNT(*) FROM pj_galleries WHERE project = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $pjInfo['pj_id']);
$stmt->execute();
$row = $stmt->get_result()->fetch_row();
$galTotal = $row[0];
于 2012-12-04T23:02:50.480 回答