简体   繁体   中英

PHP - SQL query is not returning any results

I must be missing something very obvious here, but I don't understand what I am doing wrong here. For some reason, $row is coming out empty, which should not happen. I am getting no error though.

$uname=mysqli_real_escape_string($conn,$_SESSION["username"]);
$query1="SELECT user_id FROM users WHERE username='$uname'";

$results=$conn->query($query1);
if($results->num_rows>0){
    while($row=$results->fetch_assoc()){
        $uid=mysqli_real_escape_string($row["user_id"]);
    }
}

I am sorry if this is a bad question, I will delete it right after, but I would appreciate any help.

No question is a bad question imo..we are all here to learn isnt it?I'd rather construct that code this way:

$uname=mysqli_real_escape_string($conn,$_SESSION["username"]);
$query1=mysqli_query($conn, "SELECT user_id FROM users WHERE username='$uname'");

if ($query1){
   while ($row = mysqli_fetch_assoc($query1){
      $user_id = $row['user_id'];
      echo $user_id;
   }
}

Try this

    $uname=mysqli_real_escape_string($conn,$_SESSION["username"]);
$query1="SELECT user_id FROM users WHERE username=
'$uname'";

$results=mysqli_query($conn, $query1);
if(mysqli_num_rows($results) >0){
    $row=$results->fetch_assoc();
    $uid=$row["user_id"];
}

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