I’ve got a website where I connect to a mySQL database to make a number of queries, in the usual fashion. I’m not doing anything more complicated than:
$result = mysql_query('SELECT * FROM table WHERE condition = "'.mysql_real_escape_string($_POST['condition']).'"');
$row = mysql_fetch_assoc($result);
echo $row['var1'].' '.$row['var2'];
And it works. But I’ve been reading up about prepared statements and they seem to offer more security and I’d like to use them and replace my database calls with some prepared statements, so I’ve been looking at the mysqli class.
But it seem so much more code to achieve the same thing. I understand I’d have to do this to get the above:
$stmt = $db->stmt_init();
if($stmt->prepare('SELECT * FROM table WHERE condition = ?')) {
$condition = $_POST['condition'];
$stmt->bind_param('s', $condition);
$stmt->execute();
$stmt->bind_result($var1, $var2, ...);
if ($stmt->fetch()) {
echo $var1 . ' - ' . $var2;
}
}
So it seems like a hell of a lot more code, and a bit harder to manage. Am I misunderstanding how to use these or is there a shorter way of doing the “normal” PHP things:
- Populating $row, being an array representing one single line from the database.
- Looping over rows, and refilling $row with the “next row” along.
- Normal UPDATE enquiries.
The above are all nice and quick to do “normally” but seem like they would take many more lines using prepared statements.
A common way is to wrap database functionality into a class. Here’s a simple one implementing caching of the prepared statements:
Usage of this is very close to the older database interfaces. Example: