使用PHP更新mysql中的非空输入值

i have a database contain thousands of row, the user can update his/her row by providing the updated values, i need to update the row only with a non null values provided by the user, if the value provided by user is null the previous data should be remain, for example:

id=1
name = John
address = USA

if the user provide name with null value and address with UK value then the data should be:

id=1
name =John
address = UK

any help with php code example will be highly appreciated.

You should loop through the $_POST superglobal and construct a new array for insertion that does not include the nulls, then use that for your query instead of $_POST directly.

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

Then use $update for your query parameters, which should not contain any null or blank values.

I use PDO connection

First create a table and insert as follows

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 to update using a non null value from database, then substitute the code below in the query statements

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

        $resultn->execute(array(
            ':name' => 'sectona'
    ));