-1

I'm running PHP 7.0 and connected to a mysql db with a record matching the query in the below:

$query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($query);
print_r($row[0]);

Print outputs 1, as expected as there is only one record matching that username.

However, the following function returns false

function user_exists(){
$exists_query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($exists_query);
return ($row[0] == 1) ? True : False;
}

But I would expect it to be true. Am I misusing the fetch function?

Luke
  • 1
  • 2

2 Answers2

-1

What exactly does your first print_r statement output? It should print an array, not an integer. Your $row is an array of arrays. So $row[0] will not be '1' but something like array('1').

trs
  • 1,038
  • 9
  • 19
  • When you have basic problems like this, play with `var_dump`. E.g. `var_dump($row)` and `var_dump($row[0])` to see what those variables contain. – trs Aug 07 '17 at 00:01
-1

I think it's because the $conn is not accessible. Try this

function user_exists(){
    global $conn;
    $exists_query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
    $row = mysqli_fetch_row($exists_query);
    return ($row[0] == 1) ? True : False;
}

Edit: As mentioned by @trs, you should consider your $row[0] output.

Junaid
  • 1,270
  • 3
  • 14
  • 33
  • 1
    You say `$conn` is not accessible then produce an answer where `$conn` is still not accessible – Phil Aug 07 '17 at 00:06
  • I copied the code but while writing the answer, totally forgot to add the `global $conn`. My bad – Junaid Aug 07 '17 at 01:03