PHP updateFromVals


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

Here is a small function that I use to update records in a database.

It coincides with the insertFromPost function that I have posted earlier.

The element names in the form need to have the same name as in the DB and the field names should all have a sort of prefix ex, auto_ user_ survey\_taker\_, etc...


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. // Function: UpdateFromVals
  4. //
  5. // Build an update statement from an associative array.
  6. //
  7. // $table -> The table in the db that you want to update
  8. // $prefix -> The prefix for the fields ( auto_ , user_ , etc... )
  9. // $key -> the field that is the key ( auto_id, user_id )
  10. // $value -> the value that the key should match ( user_id = 37 )
  11. // $vals -> the associative array with data, defaults to _POST
  12. //
  13. function updateFromVals( $table , $prefix , $key , $value , $vals = null )
  14. {
  15. $fields = array();
  16.  
  17. if( is_null( $vals ) )
  18. {
  19. $vals = $_POST;
  20. }
  21.  
  22. // loops through the vals and build it up
  23. foreach( $vals as $k => $v )
  24. {
  25. // do we have the right prefix?
  26. if( ereg( "^".$prefix , $k ) )
  27. {
  28. $fields[] = mysql_escape_string( $k ) . " = '".mysql_escape_string( $v )."'";
  29. }
  30. }
  31.  
  32. // remove the last ", "
  33. $fields = join( ", " , $fields );
  34.  
  35.  
  36. // construct the query in full
  37. $q = "UPDATE ".$table." SET ".$fields." WHERE ".$key." = '".$value."'";
  38. return $q;
  39. }
  40.  
  41.  
  42. /// testing code here:
  43. /// probably not what you want to copy
  44. /// illustrative purposes only
  45.  
  46.  
  47. $test['user_name'] = "Doe";
  48. $test['user_fname'] = "John";
  49. $test['user_birthday'] = "1977-12-16 00:00:00";
  50. $test['user_favorite_color'] = "orange";
  51. $test['user_attempted_injection'] = "a string with a \"'\" can be dangerous in a db statement";
  52.  
  53.  
  54. $q = updateFromVals( "users" , "user_" , "user_id" , 44 , $test );
  55. echo $q;
  56.  
  57.  
  58.  
  59. ?>

URL: http://www.goingson.be

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.