Guest User

Untitled

a guest
Aug 17th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. converting raw queries to prepared statement
  2. function prepare1995Sql_EXAMPLE ($sqlString) {
  3.  
  4. # regex pattern
  5. $patterns = array();
  6. $patterns[0] = '/'.*?'/';
  7.  
  8. # best to use question marks for an easy example
  9. $replacements = array();
  10. $replacements[0] = '?';
  11.  
  12. # perform replace
  13. $preparedSqlString = preg_replace($patterns, $replacements, $sqlString);
  14.  
  15. # grab parameter values
  16. $pregMatchAllReturnValueHolder = preg_match_all($patterns[0], $sqlString, $grabbedParameterValues);
  17. $parameterValues = $grabbedParameterValues[0];
  18.  
  19. # prepare command:
  20. echo('$stmt = $pdo->prepare("' . $preparedSqlString . '");');
  21. echo("n");
  22.  
  23. # binding of parameters
  24. $bindValueCtr = 1;
  25. foreach($parameterValues as $key => $value) {
  26. echo('$stmt->bindParam(' . $bindValueCtr . ", " . $value . ");");
  27. echo("n");
  28. $bindValueCtr++;
  29. }
  30.  
  31. # if you want to add the execute part, simply:
  32. echo('$stmt->execute();');
  33. }
  34.  
  35. # TEST!
  36. $sqlString = "SELECT foo FROM bar WHERE name = 'foobar' or nickname = 'fbar'";
  37. prepare1995Sql_EXAMPLE ($sqlString);
  38.  
  39. $stmt = $pdo->prepare("SELECT foo FROM bar WHERE name = ? or nickname = ?");
  40. $stmt->bindParam(1, 'foobar');
  41. $stmt->bindParam(2, 'fbar');
  42. $stmt->execute();
Add Comment
Please, Sign In to add comment