I have the following code:
$mySQL = sqlStart("databaseName"); // This is just a function I use to connect to a database.
$query="SELECT id FROM users WHERE last_name='?' AND first_name='?'";
if ($statement = $mySQL->prepare($query)) {
if (!$statement->bind_param("ss", $firstname, $lastname)) {
$update["error"] = $statement->error;
}
if (!$statement->execute()) {
$update["error"] = $statement->error;
}
if (!$statement->bind_result($userid)) {
$update["error"] = $statement->error;
}
while ($statement->fetch()) {
$update["userid"] = $userid;
}
$statement->close();
}
$mySQL->close();
I am trying to securely query a database for a single result. The function seems very inefficient and I'm looking for suggestions on how to clean it up. There are many times that I need to query a database for a single result and having this whole thing for each query seems a bit ridiculous. I know I can turn it into a function and just call that every time, which I will eventually do, but I want to refine this first.
Is there a shorter way I can securely get something from a db? I need to make sure SQL injection is prevented.
Thanks.