0

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.

the4tress
  • 542
  • 6
  • 19
  • 2
    Not sure what you're trying to do here... your `$query` string has `$lastname` and `$firstname` variables embedded in it, and no placeholders for parameter binding... but then you're trying to use it to bind the `$userid` field??? It looks to me like you've got the wrong query string in the question. – Spudley Nov 15 '13 at 15:20
  • *"I need to make sure SQL injection is prevented."* - Then read [this article](http://stackoverflow.com/q/60174/1415724) and [this one also](https://www.owasp.org/index.php/Top_10_2013-Top_10) and make sure you fully understand everything. – Funk Forty Niner Nov 15 '13 at 15:37
  • Spudley: I already know the user's first and last name which are loaded in $firstname and $lastname. I'm finding that user's ID in the table based on their first and last name. That part works correctly. I just tested it to make sure. – the4tress Nov 15 '13 at 15:42
  • Fred: So looking at your first link it looks like I'm doing it the same way, just with error handling. I guess I'll just stick to the method I'm using then. Thanks. – the4tress Nov 15 '13 at 15:47
  • Spudley: crap, I see exactly what you are saying now. I updated the query above. – the4tress Nov 15 '13 at 15:50
  • Why do you consider this inefficient? Is it the MySQL that you don't like? Is it the amount of PHP code required to handle that MySQL query? – AgRizzo Nov 15 '13 at 16:37
  • AgRizzo: It just seems like a lot of code for something that should be able to be done in fewer lines. Plus the while loop seems excessive. – the4tress Nov 15 '13 at 17:19

0 Answers0