Search code examples
phpmysqlfeedback

Can I get feedback on this PHP function that tests if a user has signed up?


I'm just getting started on writing functions instead of writing everything inline. Is this how a reusable function is typically written?

function test_user($user) {
$conn = get_db_conn();
$res = mysql_query("SELECT * FROM users WHERE uid = $user");
$row = mysql_fetch_assoc($res);
if (count($row) == 1) {
return true;
}
else {
    return false;
}
}

When someone logs in, I have their UID. I want to see if that's in the DB already. It's basic logic will be used in a

"If exists, display preferences, if !exists, display signup box" sort of flow. Obviously it's dependent on how it's used in the rest of the code, but will this work as advertised and have I fallen for any pitfalls? Thanks!


Solution

  • Try this:

    $conn = get_db_conn(); # should reuse a connection if it exists
    
    # Have MySQL count the rows, instead of fetching a list (also prevent injection)
    $res = mysql_query(sprintf("SELECT COUNT(*) FROM users WHERE uid=%d", $user));
    
    # if the query fails
    if (!$res) return false;
    
    # explode the result
    list($count) = mysql_fetch_row($res);
    return ($count === '1');
    

    Thoughts:

    • You'll want better handling of a failed query, since return false means the user doesn't already exist.

    • Use the database to count, it'll be faster.

    • I'm assuming uid is an integer in the sprintf statement. This is now safe for user input.

    • If you have an if statement that looks like if (something) { true } else { false } you should collapse it to just return something.

    HTH