PHP 从表单到MySQL DB的简单INSERT,UPDATE

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 从表单到MySQL DB的简单INSERT,UPDATE相关的知识,希望对你有一定的参考价值。

<?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>

以上是关于PHP 从表单到MySQL DB的简单INSERT,UPDATE的主要内容,如果未能解决你的问题,请参考以下文章

PHP 仅以登录形式从 MySQL DB 中获取最后一行

php-php连接数据库

使用PHP为MYSQL中的所有表单变量(POST/GET)创建INSERT

php + mysql 插入错误

从以下位置插入/转换日期:C++ 到 mySQL db

从 4.1 升级到 MySQL 5.5 后,Php-MySQL UPDATE & INSERT 停止工作