MYSQLI_NUM_ROWS ALWAYS RETURNING 0

2019-04-18 00:14发布

问题:

i'm trying to get rid of a bug ASAP. I'm using mysql_num_rows but it ALWAYS returns 0. And i dont know if it's because i have the wrong syntax or what... can you guys help me? here's the code;

<?php
include_once("checklogin.php");
$u = "";
if(isset($_GET["u"])){
    $u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
    header("location: http://www.myswesite.com/login.php");
    exit();    
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($connection, $sql);
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
    echo "User does not exist or is not yet activated, press back";
    exit(); 
}
?>

回答1:

i think there is a syntax error in your query when you are passing username try this i think it works for you.

$username=$_SESSION['username'];
   SELECT * FROM tbl_users WHERE Username='".$username."'


回答2:

You have to use store_result to buffer the result set before you can get the num rows.

$user_query = mysqli_query($connection, $sql);
mysqli_store_result($connection);
$numrows = mysqli_num_rows($user_query);

See http://www.php.net/manual/en/mysqli-result.num-rows.php:

For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.