简体   繁体   中英

MySQL SELECT COUNT returning NULL

I'm trying to get the number of comments on a particular item.

$stmt1 = $conn->prepare("SELECT COUNT(r_value) FROM ratings WHERE r_snippet=? AND r_value=3 OR r_value=2");
$stmt2 = $conn->prepare("SELECT COUNT(c_id) FROM comments WHERE c_snippet=?");

foreach ($snippets as $snippet){

    $s_id = $snippet['s_id'];
    $s_thumb = $snippet['s_thumb'];

    $stmt1->bind_param("i",$s_id);
    $stmt1->execute();
    $stmt1->bind_result($numLikes);
    $stmt1->fetch();

    $stmt2->bind_param("i",$s_id);
    $stmt2->execute();
    $stmt2->bind_result($numComments);
    $stmt2->fetch();

?>

    ** HTML here **    

<?php 

}

$stmt1->close();
$stmt2->close();

?>

$numLikes works fine, but $numComments seems to be returning NULL (from var_dump ) and I'm not sure why. The SQL in phpMyAdmin works fine and returns the number of comments...

You probably want change this for your first query

... AND r_value=3 OR r_value=2

To

... AND (r_value=3 OR r_value=2)

OR THIS

... AND r_value IN (2,3)

But for the second query try something simple just for debug

$stmt2 = $conn->prepare("SELECT * FROM comments WHERE c_snippet=10");

then

$stmt2 = $conn->prepare("SELECT count(*) FROM comments WHERE c_snippet=10");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM