我正在尝试从我的数据库表中获取所有注释投票,该表属于$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 |
+----+---------+------+
我最初的方法与您的方法非常相似,并且像您的方法一样失败了。一些研究表明,这种方法不起作用,因为我们都发现$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');
由于某种原因,我无法让绑定工作。但是,我通过使用$stmt = $db_conn->connect->prepare("SELECT
ITEM_ID FROM
COMMENT_VOTES WHERE VOTE > 0 AND
ITEM_ID IN ($comment_ids)");
让它在没有绑定的情况下工作