使用PHP只更新mysql中的not null输入值


update only not null input value in mysql using PHP

我有一个包含数千行的数据库,用户可以通过提供更新的值来更新他/她的行,我只需要使用用户提供的非null值来更新行,如果用户提供的值为null,则应保留以前的数据,例如:

id=1
name = John
address = USA

如果用户提供的名称为空值,地址为英国值,则数据应为:

id=1
name =John
address = UK

任何有关php代码示例的帮助都将不胜感激。

您应该循环遍历$_POST超全局,并构造一个不包括null的新数组进行插入,然后将其直接用于查询,而不是$_POST

$update = array();
foreach ($_POST as $key => $value) {
    if(!is_null($value) && !($value == ''))
        $update[$key] = $value;
}

然后对查询参数使用$update,该参数不应包含任何null或空白值。

我使用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';
?>

finall使用数据库中的非null值进行更新,然后在查询语句中替换以下代码

$resultn = $db->prepare('SELECT * FROM testing where name = :name');
        $resultn->execute(array(
            ':name' => 'sectona'
    ));