Posted By

KF on 09/24/09


Tagged


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

KF
4rp70x1n
dantreacy


mysqli Prepared Statements


 / Published in: MySQL
 

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

  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. to
  40. SELECT Name FROM City WHERE name = ?;
  41.  
  42. Here IS a more complete example that demonstrates the entire process:
  43.  
  44. <?php
  45. $mysqli = new mysqli('localhost', 'user', 'password', 'world');
  46.  
  47. /* check connection */
  48. if (mysqli_connect_errno()) {
  49. printf("Connect failed: %s\n", mysqli_connect_error());
  50. exit();
  51. }
  52.  
  53. $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
  54. $stmt->bind_param('sssd', $code, $language, $official, $percent);
  55.  
  56. $code = 'DEU';
  57. $language = 'Bavarian';
  58. $official = "F";
  59. $percent = 11.2;
  60.  
  61. /* execute prepared statement */
  62. $stmt->execute();
  63.  
  64. printf("%d Row inserted.\n", $stmt->affected_rows);
  65.  
  66. /* close statement and connection */
  67. $stmt->close();
  68.  
  69. /* Clean up table CountryLanguage */
  70. $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
  71. printf("%d Row deleted.\n", $mysqli->affected_rows);
  72.  
  73. /* close connection */
  74. $mysqli->close();
  75. ?>
  76.  
  77. 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.
  78.  
  79. 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.
  80.  
  81. 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.
  82.  
  83. $stmt->bind_param('s', $foo);
  84. $stmt->bind_param('si', $foo, $bar);
  85. $stmt->bind_param('sid', $foo, $bar, $baz);
  86.  
  87. The bind TYPES let the mysqli extension know how to encode the data that it sends for greater efficiency.
  88.  
  89. 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.
  90.  
  91. There IS also a special type that allows long blobs to be sent to the MySQL server IN chunks.
  92.  
  93. The following table shows the TYPES AND WHEN to USE them:
  94.  
  95. BIND TYPE COLUMN TYPE
  96. i All INT TYPES
  97. d DOUBLE AND FLOAT
  98. b BLOBs
  99. s All other TYPES

Report this snippet  

You need to login to post a comment.