Posted By

brownrl on 06/24/09


Tagged

form database insert


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

jseltzer
xmartyxcorex


PHP InsertFromVals


 / Published in: PHP
 

URL: http://www.itsgotto.be/cv.php

This is a long over due update to my db insert building function. Please not that the function is the important part the code below is just prove that it works... l:-)

  1. <?php
  2.  
  3.  
  4. // Function: Insert From Vals
  5. // Take an associative array and build an insert statement
  6. //
  7. // $table -> the table you want to fill
  8. // $prefix -> the prefix of the fields ( ie, auto_color -> 'auto_' )
  9. // $vals -> the array to insert, default _POST
  10. //
  11. // Please note that this will work with normal database naming and not with
  12. // special names with spaces and accents and odd stuff
  13. //
  14. //
  15. function insertFromVals( $table , $prefix , $vals = null )
  16. {
  17. $fields = array();
  18. $vallues = array();
  19.  
  20. if( is_null( $vals ) )
  21. {
  22. $vals = $_POST;
  23. }
  24.  
  25. foreach( $vals as $k => $v )
  26. {
  27. if( preg_match( "/^".$prefix."/" , $k ) )
  28. {
  29. $fields[] = mysql_escape_string( $k );
  30. $values[] = mysql_escape_string( $v );
  31. }
  32. }
  33. $fields = join( "," , $fields );
  34. $values = "'" . join( "', '" , $values ) ."'";
  35.  
  36. $q = "INSERT INTO ".$table." (".$fields.") VALUES (".$values.")";
  37.  
  38. return $q;
  39. }
  40.  
  41.  
  42.  
  43. /// testing code here:
  44. /// probably not what you want to copy
  45. /// illustrative purposes only
  46.  
  47.  
  48. $test['user_name'] = "Doe";
  49. $test['user_fname'] = "John";
  50. $test['user_birthday'] = "1977-12-16 00:00:00";
  51. $test['user_favorite_color'] = "orange";
  52. $test['user_attempted_injection'] = "a string with a \"'\" can be dangerous in a db statement";
  53.  
  54.  
  55. $q = insertFromVals( "users" , "user_" , $test );
  56.  
  57. echo $q;
  58.  
  59.  
  60. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: MMDeveloper on June 24, 2009

you might want to escape the field names as well

Posted By: brownrl on June 25, 2009

yes you are correct sorry older version that was copied and pasted.

UPDATE MADE

You need to login to post a comment.