Posted By


brownrl on 06/24/09

Tagged


Statistics


Viewed 666 times
Favorited by 1 user(s)

PHP InsertFromVals


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

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:-)


Copy this code and paste it in your HTML
  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. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.