I am just looking for clarification on the most efficient way of querying a large SQL database using MySQLi queries.
For a user registration form, I am looking to check the users table in an SQL database (not necessarily called users for security reasons) if the username entered into the form already exists. For large user tables, if efficient queries are not used, this could drag the website speed down.
As a point of note, each user in the table has a unique id
.
With using LIMIT 1
in the following MySQLi query, I can stop the query after 1 was found matching.
$username = $_POST['username'];
$database = mysqli_connect($dbServer, $dbUser, $dbPassword, $dbName);
$query = "SELECT `username` FROM `".$table."` WHERE `username` ='".mysqli_real_escape_string($database, $username)."' LIMIT 1";
if (mysqli_query($database, $query)) {
die ("User exists");
}
I am led to believe that the following is more efficient
$username = $_POST['username'];
$database = mysqli_connect($dbServer, $dbUser, $dbPassword, $dbName);
$query = "SELECT `username` FROM `".$table."` WHERE `username` ='".mysqli_real_escape_string($database, $username)."'";
$result = mysqli_query($database, $query);
if (mysqli_num_rows($result) > 0) {
die ("User exists");
}
but, I would have thought that the query is still being called to create the $result
and with no LIMIT
set it would slow things down. Am I correct? Which will be more efficient?