Online training and video tutorials
Enter     Registration
     Contacts

 
     
 
Max Azimov
St. Petersburg

Articles [97]

User's video [259]





PHP Prepared Statements
 
Prepared statements are very useful against SQL injections.
 
Prepared Statements and Bound Parameters
 
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
 
Prepared statements basically work like this:
  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
  2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
  3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values
 
Compared to executing SQL statements directly, prepared statements have two main advantages:
 
  • Prepared statements reduces parsing time as the preparation on the query is done only once (although the statement is executed multiple times)
  • Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query
  • Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.
 
Prepared Statements in MySQLi
 
The following example uses prepared statements and bound parameters in MySQLi:
 
Example (MySQLi with Prepared Statements)
  1. <?php
  2. $servername = "localhost";
  3. $username = "username";
  4. $password = "password";
  5. $dbname = "myDB";
  6. // Create connection
  7. $conn = new mysqli($servername, $username, $password, $dbname);
  8. // Check connection
  9. if ($conn->connect_error) {
  10.     die("Connection failed: " . $conn->connect_error);
  11. }
  12. // prepare and bind
  13. $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
  14. $stmt->bind_param("sss", $firstname, $lastname, $email);
  15. // set parameters and execute
  16. $firstname = "John";
  17. $lastname = "Doe";
  18. $email = "john@example.com";
  19. $stmt->execute();
  20. $firstname = "Mary";
  21. $lastname = "Moe";
  22. $email = "mary@example.com";
  23. $stmt->execute();
  24. $firstname = "Julie";
  25. $lastname = "Dooley";
  26. $email = "julie@example.com";
  27. $stmt->execute();
  28. echo "New records created successfully";
  29. $stmt->close();
  30. $conn->close();
  31. ?>
 
Code lines to explain from the example above:
  1. "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"
In our SQL, we insert a question mark (?) where we want to substitute in an integer, string, double or blob value.
 
Then, have a look at the bind_param() function:
  1. $stmt->bind_param("sss", $firstname, $lastname, $email);
 
This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
 
The argument may be one of four types:
  • i - integer
  • d - double
  • s - string
  • b - BLOB
 
We must have one of these for each parameter.
 
By telling mysql what type of data to expect, we minimize the risk of SQL injections.
 
Note: If we want to insert any data from external sources (like user input), it is very important that the data is sanitized and validated.
 
 
Prepared Statements in PDO
 
The following example uses prepared statements and bound parameters in PDO:
 
Example (PDO with Prepared Statements)
  1. <?php
  2. $servername = "localhost";
  3. $username = "username";
  4. $password = "password";
  5. $dbname = "myDBPDO";
  6. try {
  7.     $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  8.     // set the PDO error mode to exception
  9.     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  10.     // prepare sql and bind parameters
  11.     $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
  12.     VALUES (:firstname, :lastname, :email)");
  13.     $stmt->bindParam(':firstname', $firstname);
  14.     $stmt->bindParam(':lastname', $lastname);
  15.     $stmt->bindParam(':email', $email);
  16.     // insert a row
  17.     $firstname = "John";
  18.     $lastname = "Doe";
  19.     $email = "john@example.com";
  20.     $stmt->execute();
  21.     // insert another row
  22.     $firstname = "Mary";
  23.     $lastname = "Moe";
  24.     $email = "mary@example.com";
  25.     $stmt->execute();
  26.     // insert another row
  27.     $firstname = "Julie";
  28.     $lastname = "Dooley";
  29.     $email = "julie@example.com";
  30.     $stmt->execute();
  31.     echo "New records created successfully";
  32.     }
  33. catch(PDOException $e)
  34.     {
  35.     echo "Error: " . $e->getMessage();
  36.     }
  37. $conn = null;
  38. ?>
 


2016-12-10
462 views




 
     
 
Map      Distance education, online learning courses. Project PLANETSTUDY - distance learning online.
© 2012 PlanetStudy

Catalog.299.ru

The site is a media provider
Яндекс.Метрика
 
English USA
Australia Русский