我有一个包含数千行的数据库,用户可以通过提供更新的值来更新他/她的行,我需要使用用户提供的非空值来更新行,如果用户提供的值是null应保留以前的数据,例如:
id=1
name = John
address = USA
如果用户提供名称为空值且地址为UK值,则数据应为:
id=1
name =John
address = UK
任何有关PHP代码示例的帮助都将受到高度赞赏。
答案 0 :(得分:1)
你应该循环遍历$_POST
超全局并构造一个不包含空值的新插入数组,然后直接将其用于查询而不是$_POST
。
$update = array();
foreach ($_POST as $key => $value) {
if(!is_null($value) && !($value == ''))
$update[$key] = $value;
}
然后使用$update
作为查询参数,不应包含任何空值或空值。
答案 1 :(得分:-1)
我使用PDO连接
首先创建一个表并插入如下
create table testing(id int(11), name varchar(100),address varchar(200));
insert into testing values(100,'Null','California');
insert into testing values(200,'sectona','California');
pdo_connect.php
<?php
$db = new PDO (
'mysql:host=localhost;dbname=yourdbname;charset=utf8',
'root', // username
'root' // password
);
?>
<?php
pdo_connect.php
// from form inputs
/*
$id=$_POST["id"];
$name=$_POST["name"];
$address=$_POST["address"];
*/
// direct variable initialisation
/*
$id='100';
$name = 'John';
$name = 'Null';
$address = 'California';
*/
// initialize a null value
$check ='Null';
// check null value for name variable in the first insert statement
$resultn = $db->prepare('SELECT * FROM testing where name = :name');
$resultn->execute(array(
':name' => 'Null'
));
while ($row = $resultn->fetch())
{
$nm = $row['name'];
}
if ($nm == $check)
{
echo '<b><font color=red><b></b>You cannot update with a Null Value</font></b>';
exit();
}
// update if name is not null
$update = $db->prepare('
UPDATE testing SET
name = :name,address = :address
WHERE id= :id');
$update->execute(array(
':name' => 'yourname',
':address' => 'USA',
':id' => '100'
));
echo 'update successful';
?>
使用数据库中的非空值进行更新,然后在查询语句中替换下面的代码
$resultn = $db->prepare('SELECT * FROM testing where name = :name');
$resultn->execute(array(
':name' => 'sectona'
));