使用mysqli预处理语句选择distinct?

时间:2014-05-30 19:28:00

标签: php mysqli

我正在尝试使用mysqli select distinct从mysql数据库prepared statements

然而,当我运行我的代码时,我没有得到任何错误,但我也无法从mysql数据库中获得结果!

这是我的mysqli prepared statement

$stmt = $db_conx->prepare("SELECT DISTINCT `title`, `url` FROM `$Pages`");
echo $storePages;
$stmt->execute();
$stmt->bind_result($title, $url);
$stmt->store_result();
while($line=$stmt->fetch()){
    $tvalue[] = $line;
     }

但是这段代码有效,我不想使用它,因为它不是mysqli预备语句:

$sql = "SELECT DISTINCT title, url FROM $Pages";
$query = mysqli_query($db_conx, $sql);
    while($line = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        $tvalue[] = $line;
    }

有人可以帮我解决这个问题吗?

由于

2 个答案:

答案 0 :(得分:1)

$stmt->fetch()不会返回提取的行,只返回 true false null 。请阅读documentation

结果存储在您告诉它在$stmt->bind_result()中使用的变量中。

$stmt->execute();
$stmt->bind_result($title, $url);
$stmt->store_result();
while($stmt->fetch()) {
    $tvalue[] = array('title'=>$title, 'url'=>$url);
}

如果您安装了mysqlnd(应该是enabled by default since PHP 5.4),那么fetch_all()的情况会更简单。这样你就不需要bind_result(),也不需要循环遍历行:

$stmt->execute();
$result = $stmt->get_result();
$tvalue = $result->fetch_all();

答案 1 :(得分:0)

始终检查您的返回值。总是

if( ! $stmt = $db_conx->prepare("SELECT DISTINCT `title`, `url` FROM `$Pages`") ) {
  die( $db_conx->error );
}
echo $storePages;
if ( ! $stmt->execute() ) {
  die( $stmt->error );
}
$stmt->bind_result($title, $url);
$stmt->store_result();

while($line = $stmt->fetch()){
  $tvalue[] = $line;
}