MySQL INSERT Query Generator w/ Strings


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

Takes your table name and key=>value array of values and returns the text for inserting into a MySQL database. Automatically surrounds strings with single quotes.


Copy this code and paste it in your HTML
  1. function get_insert_query($table, $array) {
  2. $insert_text = "INSERT INTO " . $table;
  3. $keys = array();
  4. $values = array();
  5. foreach ($array as $k=>$v) {
  6. $keys[] = $k;
  7. $values[] = $v;
  8. }
  9. $key_string = "(";
  10. foreach ($keys as $key) {
  11. $key_string = $key_string . $key . ", ";
  12. }
  13. $key_string = substr($key_string, 0, -2);
  14. $insert_text = $insert_text . " " . $key_string . ")";;
  15. $insert_text = $insert_text . " VALUES ";
  16. $value_string = "(";
  17. foreach ($values as $value) {
  18. if (gettype($value) == "string") {
  19. $value_string = $value_string . "'" . $value . "', ";
  20. }
  21. else {
  22. $value_string = $value_string . $value . ", ";
  23. }
  24. }
  25. $value_string = substr($value_string, 0, -2);
  26. $insert_text = $insert_text . $value_string . ")";
  27. return $insert_text;
  28. }
  29.  
  30. $data = array('id' => 23, 'name' => 'David Lemcoe', 'address' => '123 Green St.');
  31. echo get_insert_query("users", $data);
  32. ## Echos: INSERT INTO users (id, name, address) VALUES (23, 'David Lemcoe', '123 Green St.')

URL: http://blog.lemcoe.com/?p=61

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.