Return to Snippet

Revision: 16055
at June 27, 2011 19:21 by brownrl


Updated Code
<?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 )
{	
	$fields = array();
	
	if( is_null( $vals ) )
	{
		$vals = $_POST;
	}
	
    // loops through the vals and build it up
	foreach( $vals as $k => $v )
	{
		// do we have the right prefix?
		if( ereg( "^".$prefix , $k ) )
		{
			$fields[] = mysql_escape_string( $k ) . " = '".mysql_escape_string( $v )."'";
		}
	}

	// remove the last ", "
	$fields = join( ", " , $fields );
	

    // 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;



?>

Revision: 16054
at July 24, 2009 11:08 by brownrl


Initial Code
// updateFromPost
//
// Take values from the _POST array and update a row in the table
//
// $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 )
//
function updateFromPost( $table , $prefix , $key , $value )
{	
        // go through the post
	foreach( $_POST as $k => $v )
	{
                // does the field have the proper prefix?
		if( ereg( "^".$prefix , $k ) )
		{
                        // add it to the query
			$fields .= mysql_escape_string( $k ) . " = '".mysql_escape_string( $v )."', ";
			
		}
	}

	// remove the last ", "
	$fields = ereg_replace( ", $" , "" , $fields );

        // construct the query in full	
	$q = "UPDATE ".$table." SET ".$fields." WHERE ".$key." = '".$value."'";
	return $q;
}

Initial URL
http://www.goingson.be

Initial Description
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...

Initial Title
PHP updateFromVals

Initial Tags
mysql, post, update

Initial Language
PHP