-1

我正在尝试对我的数据库进行计数,除非其中一个用户名包含撇号,否则它可以正常工作。

我正在使用准备好的语句,所以我假设它被正确转义了?

有人可以告诉我有什么问题吗?

$var1 = $_SESSION['SESS_STAFF_NAME'];
$qry = "SELECT COUNT(*) FROM tbl WHERE staff = ?" ;
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('s', $var1);                          
$stmt->execute();
$result = $stmt->get_result();
$total_items = $result->fetch_row();
$rows = $total_items[0];
echo $rows; 

只有当人员变量包含时,我才会遇到错误问题',例如“O'Connor”;它似乎返回了所有记录的总数。

4

1 回答 1

-1

通常,这与 PDO 准备语句是一样的:查询是预编译的,这保证了对 SQL 注入的保护。无需转义绑定参数。

测试 :

ThinkPad-T420 ~ $ cat test.php
#!/usr/bin/php
<?php
    $var = "String' thing"; // It's working too with $var = 'String\' thing'
    $dbh = new mysqli("localhost", "root", "sitri", "test");
    $sql = "SELECT COUNT(*) AS nb FROM t WHERE field = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->bind_param('s', $var);
    $stmt->execute();
    $result = $stmt->get_result();
    $total_items = $result->fetch_assoc();
    echo "total=" . $total_items['nb'] . "\n";
?>
ThinkPad-T420 ~ $ echo "DESC t"|mysql -uroot -p"${passwd}" test
Field   Type    Null    Key Default Extra
field   varchar(254)    YES     NULL    
ThinkPad-T420 ~ $ echo "SELECT * FROM t;"|mysql -uroot -p"${passwd}" test
field
String' thing
ThinkPad-T420 ~ $ ./test.php 
total=1
于 2013-11-02T11:05:06.790 回答