Mysqli查询只返回一行(最后一行)

问题描述 投票:0回答:2

我试图从我的数据库表中获得所有评论投票,这些投票属于$comments变量中的注释(在comment_votes表中称为item_id)并且> 0。但是,我只得到一个投票行(最后一个)运行下面的脚本。根据下面的数据库表值,我认为我应该有4.做IN()只返回一行或我做错了什么?

$comments = "1,3,4,5,6,7,11,12,13";

$db_conn = new Database;
$stmt = $db_conn->connect->prepare("SELECT ID FROM `COMMENT_VOTES` WHERE VOTE > 0 AND `ITEM_ID` IN (?)");
$stmt->bind_param("s", $comments);
$stmt->execute();
$result = $stmt->get_result();

$votes = [];

while ($row = $result->fetch_assoc()) { 

    array_push($votes, $row['ID']);

}

$votes = implode(",",$votes);
echo $votes;

+---------------------+
|    COMMENT_VOTES    |
+----+---------+------+
| ID | ITEM_ID | VOTE |
+----+---------+------+
| 1  | 12      | 1    |
| 2  | 8       | 0    |
| 3  | 3       | 1    |
| 4  | 22      | 1    |
| 5  | 5       | 0    |
| 6  | 5       | 1    |
| 7  | 5       | 1    |
| 8  | 5       | 0    |
+----+---------+------+
php mysqli
2个回答
1
投票

我接近这个的最初方法与你的方法非常相似,就像你失败一样。一个小小的研究表明这种方法不会像我们都发现的那样工作,因为$comments字符串中的每个项目确实需要它自己的占位符和相关的类型字符串,这导致我这样:

/* output */
$votes=array();

/* original string of IDS */
$comments='1,3,4,5,6,7,11,12,13';

/* create an array from IDS */
$array=explode(',',$comments);

/* create placeholders for each ID */
$placeholders=implode( ',', array_fill( 0, count( $array ), '?' ) );

/* create a type string for each - all going to be `i` */
$types=implode( '', array_fill( 0, count( $array ), 'i' ) );

/* create the sql statement */
$sql=sprintf( 'select `id` from `comment_votes` where `vote` > 0 and `item_id` in ( %s );', $placeholders );

/* create the prepared statement */
$stmt = $db->prepare( $sql );

/* Add the type strings to the beginning of the array */
array_unshift( $array, $types );

if( $stmt ){

    /* bind types and placeholders - 2nd arg passed by reference */
    call_user_func_array( array( $stmt, 'bind_param'), &$array );

    /* execute the query */
    $result=$stmt->execute();

    /* success */
    if( $result ){

        $stmt->store_result();
        $stmt->bind_result( $id );
        $rows=$stmt->num_rows;

        printf( 'rows found: %d<br />',$rows );

        /* add found IDs to output */
        while( $stmt->fetch() ) {
            $votes[]=$id;
        }
        /* tidy up */
        $stmt->free_result();
        $stmt->close();


        /* do something with output */
        printf( '<pre>%s</pre>', print_r( $votes, true ) );

    } else{
        exit('Error: No results');
    }

} else exit('Error: Prepared statement failed');

0
投票

由于某种原因,我无法绑定工作。但是,我通过使用$stmt = $db_conn->connect->prepare("SELECTITEM_IDFROMCOMMENT_VOTESWHERE VOTE > 0 ANDITEM_IDIN ($comment_ids)");让它无需绑定

© www.soinside.com 2019 - 2024. All rights reserved.