Prepared queries vs constructed queries

Viewed 491

I see the oft-repeated comment "always use prepared queries to protect against SQL injection attacks".

What is the practical difference between using a prepared query and a constructed query where user input is always sanitized?

Constructed

function quote($value) {
  global $db; 
  return "'" . mysqli_real_escape_string($db, $value) . "'";
}

$sql = "INSERT INTO foo (a, b) VALUES (" . quote($a) . "," . quote($b) . ")";

Prepared

$stmt = mysqli_prepare($db, "INSERT INTO foo (a, b) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "ss", $a, $b);

Aside from verbosity and style, what reasons would I want to use one over the other?

3 Answers
Related