PHP + MySQL: Checking to see if a record exists in the database

May 15, 2009

Quite often I need to look into the database to see if a record exists. For example, to check if a username already exists when creating a new user. I created a simple function to do this for me with mysqli. All I have to do is pass it the table name to look in, and the where clause. It will return true if it exists.

/**
 * Looks in the database to see if a record or records exist
 *
 * @param String $table - Which table to look in
 * @param String $where - Where clause without WHERE
 * @param Mysqli Connection
 * @return Boolean
 **/
function recordExists($table, $where, $mysqli) {
        $query = "SELECT * FROM `$table` WHERE $where";
        $result = $mysqli->query($query);

        if($result->num_rows > 0) {
                return true; // The record(s) do exist
        }
        return false; // No record found
}