1

How do i protect against SQL Injection if i wrote the site in PHP procedural? Can i use prepared statements? Or exists other ways?

example:

 $query ="INSERT INTO users (name,username,password,email,gender) VALUES ('$name','$username','$password','$email','$gender')";
 $result = mysqli_query($connect,$query) or die ( "Error : ". mysqli_error($connect) );
  • use PDO's prepared queries – Marcin Jun 16 '17 at 21:07
  • Use prepared statements. Yes, it is possible to use them with the procedural interface. See [the examples in the docs](http://php.net/manual/en/mysqli.prepare.php#refsect1-mysqli.prepare-examples). There is an OO example and a procedural example. – Don't Panic Jun 16 '17 at 21:33
  • You got a correct answer. My opinion is that PDO/mysql is easier to work with than mysqli. In either case, use parameters and the concerns about escaping or sql injection essentially go away. – gview Jun 16 '17 at 23:32

1 Answers1

1

Yes, you can write prepared statements with bound parameters in procedural code using mysqli. Here's a solution based on your example.

$query ="
    INSERT INTO users (name, username, password, email, gender)
    VALUES (?, ?, ?, ?, ?)";
if (($stmt = mysqli_prepare($connect, $sql)) === false) {
    die("Error : " . mysqli_error($connect));
}
if (mysqli_stmt_bind_param($stmt, "ssss", $name, $username, $password, $email, $gender) === false) {
    die("Error : " . mysqli_stmt_error($stmt));
}
if (mysqli_stmt_execute($stmt) === false) {
    die("Error : " . mysqli_stmt_error($stmt));
}
$result = mysqli_stmt_get_result($stmt);
if (mysqli_errno()) {
    die("Error : " . mysqli_stmt_error($stmt));
}
... fetch from $result ...
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828