douchai7891
2014-05-30 19:28
浏览 66
已采纳

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

I am trying to select distinct from mysql database using mysqli prepared statements.

however, when I run my code, I get no error at all but I cannot get the results from the mysql database either!

this is my 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;
     }

but This code works and i do not want to use it as it is not mysqli prepared statement:

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

could someone please help me out with this?

Thanks

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqba94394 2014-05-30 20:47
    已采纳

    $stmt->fetch() does not return the row fetched, it only returns true, false, or null. Please read the documentation.

    The results are stored in the variables you told it to use in $stmt->bind_result().

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

    If you have mysqlnd installed (which should be enabled by default since PHP 5.4), it would be simpler for your case to fetch_all(). That way you don't need bind_result(), nor do you need to loop over rows:

    $stmt->execute();
    $result = $stmt->get_result();
    $tvalue = $result->fetch_all();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dtt78245 2014-05-30 19:35

    Always check your return values. Always.

    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;
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题