I've been looking into security for PHP and came across MySQLi prepared statements. After doing some research I'm confused about why you would use these instead of normal SQL query. A prepared statement looks something like this:
$quer=$db->stmt_init();
if($quer->prepare("INSERT INTO `test` (`first`,`second`,`third`) VALUES (?,?,?)")) {
$quer->bind_param('iss',$aa,$bb,$cc);
$aa=1;
$bb="something";
$cc="testdata";
$quer->execute();
$quer->close();
}
How is this in any way beneficial compared to the following:
$aa=(int)1;
$bb=(string)mysql_real_escape_string("something");
$cc=(string)mysql_real_escape_string("testdata");
if($quer=@mysql_query("INSERT INTO `test` (`first`,`second`,`third`) VALUES ('$aa','$bb','$cc')")) {
// Carry on
}
else die("Error with database!");
As the prepared statement will require two requests to the MySQL server and falsely suggests that no sanitisation of data is needed - completely ignoring other attacks such as XSS, file inclusions etc.
Edit:
I also meant to ask if there are any other methods I can (feasibly) use for databases in general!