Jack The Baker
Jack The Baker

Reputation: 1883

mysqli dynamic update query

With this query I update images fields in database:

$sql = $connection->prepare('UPDATE ads img1 = ?, img2 = ?, img3 = ? WHERE id = ?');
$sql->bind_param("ssss", $nameImg1, $nameImg2, $nameImg3, $id);

But this work fine if user update all 3 images, not only one or two. if user change just one image, for example change img2, img1 and img3 going to update to empty value because I use this condition:

$img1 = $_POST["img-1-val"];
$img2 = $_POST["img-2-val"];
$img3 = $_POST["img-3-val"];

if($img1 != 'NULL'){
$nameImg1 = $date.'_'.$adsid.'_1';
} 

if($img2 != 'NULL'){
$nameImg2 = $date.'_'.$adsid.'_2';
} 

if($img3 != 'NULL'){
$nameImg3 = $date.'_'.$adsid.'_3';
}

in html:

<input type="hidden" name="img-1-val" value="NULL"/> 
<!-- this already has image -->
<input type="hidden" name="img-2-val"/>
<input type="hidden" name="img-3-val"/>

If each image has image, value is NULL if there is no image set, it is empty, if user change any image, it set base64 value.

But the main problem is, I don't want to update any img field in database if $_POST return NULL as value, already it update all fields, img1, img2, img3,and this cause of removing previously data. How can I update database field if value not equal to NULL?


Consider these codes run in edit page. Also my problem is mysqli query not if condition.

Upvotes: 0

Views: 1155

Answers (2)

Virb
Virb

Reputation: 1578

So, you have to just check with different variable with query.

This will check one by one image and if all the images have values then it will update all three images otherwise one by one. This may help.

if((isset($img1)) && ($img1 != 'NULL')){
    $nameImg1 = $date.'_'.$adsid.'_1';
    $sql = $connection->prepare('UPDATE ads img1 = ? WHERE id = ?');
    $sql->bind_param("ss", $nameImg1, $id);
} 

if((isset($img2)) && ($img2 != 'NULL')){
    $nameImg2 = $date.'_'.$adsid.'_2';
    $sql = $connection->prepare('UPDATE ads img2 = ? WHERE id = ?');
    $sql->bind_param("ss", $nameImg2, $id);
} 

if((isset($img3)) && ($img3 != 'NULL')){
    $nameImg3 = $date.'_'.$adsid.'_3';
    $sql = $connection->prepare('UPDATE ads img3 = ? WHERE id = ?');
    $sql->bind_param("ss", $nameImg3, $id);
}

Upvotes: 1

Chintan
Chintan

Reputation: 143

You can make your update query dynamic like this :

/* function to build SQL UPDATE string */
function build_sql_update($table, $data, $where)
{
    $cols = array();

    foreach($data as $key=>$val) {
        if($val != NULL) // check if value is not null then only add that colunm to array
        {
           $cols[] = "$key = '$val'"; 
        }
    }
    $sql = "UPDATE $table SET " . implode(', ', $cols) . " WHERE $where";

    return($sql);
}

In this way, only those columns will be updated which has valid values.

Upvotes: 3

Related Questions