Return to Snippet

Revision: 43806
at March 31, 2011 04:57 by mikael12


Initial Code
<?php 

$link = mysql_connect('localhost','root','');
mysql_select_db('db_name');
mysql_query('SET NAMES UTF8');

$id = 0;
$secured = array();
$secured = sanitize( $_POST );
extract($secured);

$db_data = array();
if ( isset($_POST['save']) && $id > 0 ) // update
{
	foreach ($data as $table => $value)
	{
		if ( is_array($value) && ! empty($value) )
		{
			foreach ($value as $k => $v)
			{
				$db_data[$table][] = "`$k` = '$v'";
			}
		}
	}

	foreach ($db_data as $table => $values)
	{
		if ( mysql_fetch_assoc(mysql_query("SELECT modified FROM $table LIMIT 1")) != '' )
			$values[] = '`modified` = NOW()';

		mysql_query("UPDATE $table SET " . implode(',', $values) . " WHERE id = $id LIMIT 1");
	}
}
elseif( isset($_POST['save']) ) // insert
{
	foreach ($data as $table => $value)
	{
		if ( is_array($value) && ! empty($value) )
		{
			foreach ($value as $k => $v)
			{
				$db_data[$table]['keys'][] = "`$k`";
				$db_data[$table]['values'][] = "'$v'";
			}
		}
	}

	foreach ($db_data as $table => $values)
	{
		if ( mysql_fetch_assoc(mysql_query("SELECT created FROM $table LIMIT 1")) != '' )
		{
			array_push($values['keys'], '`created`');
			array_push($values['values'], 'NOW()');
		}
		
		mysql_query("INSERT INTO $table (" . implode(',', $values['keys']) . ") VALUES (" . implode(',', $values['values']) . ")");
		$id = mysql_insert_id();
	}
}

mysql_close($link);

?>

<form action="" method="post">
	<input type="hidden" name="id" value="<?php echo $id ?>" />
	<input type="text" name="data[users][name]" />
	<input type="text" name="data[users][email]" />
	<input type="text" name="data[users][address]" />
	<input type="text" name="data[users][city]" />
	<input type="text" name="data[users][zip]" />
	<input type="text" name="data[users][web]" />
	<input type="submit" name="save" value="Save" />
</form>

Initial URL

                                

Initial Description

                                

Initial Title
Simple INSERT, UPDATE from form to MySQL DB

Initial Tags

                                

Initial Language
PHP