mysqli Prepared Statements


/ Published in: MySQL
Save to your folder(s)



Copy this code and paste it in your HTML
  1. Prepared Statements
  2. Now that we have seen the basic use of the extension, let’s examine a few of the new features.
  3.  
  4. Prepared statements provide developers with the ability to create queries that are more secure, have better performance, and are more convenient to write.
  5.  
  6. They come in two flavors: bound parameter prepared statements, and bound result prepared statements.
  7.  
  8. Bound Parameters
  9. Bound parameter prepared statements allow query templates to be created and then stored on the MySQL server. When a query needs to be made, data to fill in the template is sent to the MySQL server, and a complete query is formed and then executed.
  10.  
  11. The basic process for creating and using bound parameter prepared statements is simple.
  12.  
  13. A query template is created and sent to the MySQL server. The MySQL server receives the query template, validates it to ensure that it is well-formed, parses it to ensure that it is meaningful, and stores it in a special buffer. It then returns a special handle that can later be used to reference the prepared statement.
  14.  
  15. When a query needs to be made, data to fill in the template is sent to the MySQL server, and then a complete query is formed and then executed.
  16.  
  17. This process has some very important behaviors wrapped up in it.
  18.  
  19. The body of the query is only sent to the MySQL server once. On requests to execute the query, only the data to fill in the template needs to be delivered to the MySQL server.
  20.  
  21. Most of the work required to validate and parse the query only needs to be done a single time, instead of each time that the query is executed.
  22.  
  23. Additionally, for queries that contain a small amount of data, the overhead of sending the query is greatly reduced. For example, if you have a query like:
  24.  
  25. INSERT INTO City (ID, Name) VALUES (NULL, 'Calgary');
  26.  
  27. then each time that you execute the query, you will only need to send about 16 bytes of query data, instead of 60 or more bytes. (These approximate numbers include overhead for the foo and bar query data like the id of the prepared statement, the length of the query data for binary safety, etc, but do not include extra overhead for the query string.)
  28.  
  29. The data for the query does not need to be passed through a function like mysql_real_escape_string() to ensure that no SQL injection attacks[4] occur. Instead, the MySQL client and server work together to ensure that the sent data is handled safely when it is combined with the prepared statement.
  30.  
  31. The query templates look something like:
  32.  
  33. INSERT INTO City (ID, Name) VALUES (?, ?);
  34.  
  35. The '?' placeholders can be used in most places that could have literal data, e.g. a query could be transformed from
  36.  
  37. SELECT Name FROM City WHERE Name = 'Calgary';
  38.  
  39. SELECT Name FROM City WHERE name = ?;
  40.  
  41. Here is a more complete example that demonstrates the entire process:
  42.  
  43. <?php
  44. $mysqli = new mysqli('localhost', 'user', 'password', 'world');
  45.  
  46. /* check connection */
  47. if (mysqli_connect_errno()) {
  48. printf("Connect failed: %s\n", mysqli_connect_error());
  49. exit();
  50. }
  51.  
  52. $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
  53. $stmt->bind_param('sssd', $code, $language, $official, $percent);
  54.  
  55. $code = 'DEU';
  56. $language = 'Bavarian';
  57. $official = "F";
  58. $percent = 11.2;
  59.  
  60. /* execute prepared statement */
  61. $stmt->execute();
  62.  
  63. printf("%d Row inserted.\n", $stmt->affected_rows);
  64.  
  65. /* close statement and connection */
  66. $stmt->close();
  67.  
  68. /* Clean up table CountryLanguage */
  69. $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
  70. printf("%d Row deleted.\n", $mysqli->affected_rows);
  71.  
  72. /* close connection */
  73. $mysqli->close();
  74. ?>
  75.  
  76. Note that bind_param() has a short string as its first parameter. This is a format string that is used to specify how the data in the bound variables should be treated.
  77.  
  78. In the case of the above script, ‘sssd’ indicates that the values of the first three parameters $code, $language and $official will be sent as a strings, while the fourth parameter $percent will contain a double or float value.
  79.  
  80. For each bound variable in bind_param(), there should be another letter in the format string that specifies how the variable should be handled. e.g.
  81.  
  82. $stmt->bind_param('s', $foo);
  83. $stmt->bind_param('si', $foo, $bar);
  84. $stmt->bind_param('sid', $foo, $bar, $baz);
  85.  
  86. The bind types let the mysqli extension know how to encode the data that it sends for greater efficiency.
  87.  
  88. The type definitions are very simple: data in the bound variables will be treated as an integer value, a rational number (double) or a string.
  89.  
  90. There is also a special type that allows long blobs to be sent to the MySQL server in chunks.
  91.  
  92. The following table shows the types and when to use them:
  93.  
  94. b BLOBs
  95. s All other types

URL: http://devzone.zend.com/article/686

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.