简体   繁体   中英

mysqli_num_rows not returning what is expected

I have a user registration page. Everything is working on the page, except the check for when a username is already in use by another user. My PHP ("..." implies there is other code in between that isn't relevant):

$login = mysqli_connect("localhost","***","***","***"); // hidden for obvious reasons

function usernameTaken($name)
{
    $query = "SELECT * FROM useraccs WHERE username='$name' LIMIT 1";

    return mysqli_num_rows(mysqli_query($login,$query)) > 0;
}

...

$username = mysqli_real_escape_string($login,$_POST["username"]);

....

if (usernameTaken($username))
    $error.= "Username is already in use.<br />";

This is not working, even if I put in a string literal in the query that I KNOW is in my SQL table. In my HTML I have this:

<?php 
$query = "SELECT * FROM useraccs WHERE username='$username' LIMIT 1";

if (mysqli_num_rows(mysqli_query($login,$query)) > 0)
    $error.= "Username is already in use.<br />";

echo $error;
?>

When I submit the registration form with a username I know is in my SQL table, this code actually works ( mysqli_num_rows returns 1 as expected) and the error gets echoed). Even though the code should do the exact same thing in both scenarios, it just isn't working in the function. The functions always returns false no matter what I put into it.

The only reason I'm using a function is for aesthetics. I know I could just use the second example and it would work, but I can't for the life of me figure out why the function won't work. I'm using multiple other functions in the exact same style (but not with mysqli_num_rows ) for other parts of this page and they are working fine.

I even tried returning an array from the query in the function, but nothing comes back. I must be missing something fundamental about PHP functions...

The variable is out of the scope of the function. You can either do:

1 - Use global

$login = mysqli_connect("localhost","***","***","***"); // hidden for obvious reasons

function usernameTaken($name)
{
    global $login;
    $query = "SELECT * FROM useraccs WHERE username='$name' LIMIT 1";

    return mysqli_num_rows(mysqli_query($login,$query)) > 0;
}

2 - Put it in the functions parameters

$login = mysqli_connect("localhost","***","***","***"); // hidden for obvious reasons

function usernameTaken($name, $login)
{
    $query = "SELECT * FROM useraccs WHERE username='$name' LIMIT 1";

    return mysqli_num_rows(mysqli_query($login,$query)) > 0;
}

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