/ Published in: PHP
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...
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...
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php // Function: UpdateFromVals // // Build an update statement from an associative array. // // $table -> The table in the db that you want to update // $prefix -> The prefix for the fields ( auto_ , user_ , etc... ) // $key -> the field that is the key ( auto_id, user_id ) // $value -> the value that the key should match ( user_id = 37 ) // $vals -> the associative array with data, defaults to _POST // function updateFromVals( $table , $prefix , $key , $value , $vals = null ) { { $vals = $_POST; } // loops through the vals and build it up foreach( $vals as $k => $v ) { // do we have the right prefix? { } } // remove the last ", " // construct the query in full $q = "UPDATE ".$table." SET ".$fields." WHERE ".$key." = '".$value."'"; return $q; } /// testing code here: /// probably not what you want to copy /// illustrative purposes only $test['user_name'] = "Doe"; $test['user_fname'] = "John"; $test['user_birthday'] = "1977-12-16 00:00:00"; $test['user_favorite_color'] = "orange"; $test['user_attempted_injection'] = "a string with a \"'\" can be dangerous in a db statement"; $q = updateFromVals( "users" , "user_" , "user_id" , 44 , $test ); echo $q; ?>