Mysqli COUNT包含包含撇号的变量

时间:2013-11-02 10:51:25

标签: php mysqli

我正在尝试对我的数据库运行计数,这正常工作,除非其中一个用户名包含撇号。

我正在使用预备语句,所以我认为它正确地被转义了?

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

$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; 

当staff变量包含'时,我才会遇到错误问题,例如“奥康纳”;它似乎正在返回所有记录的总数。

1 个答案:

答案 0 :(得分:-1)

通常,这与PDO预处理语句相同:查询是预编译的,可以保证防止SQL注入。无论如何逃避绑定params。

测试:

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