Skip to content
Advertisement

NULL changes to 0 when added to the db

Ok I have tried everything I can think of, I couldn’t make it. I am creating some inputs like this:

for($l = 1; $l <= 6; $l++){
            echo '<div class="col-sm-auto" style="text-align:center;">
                <h4>QTY'.$l.'</h4>
                <input class="divtop" name="qt'.$l.$count.'" type="number" value="'.${'quantity'.$l}.'"  style="width:85px; text-align:center;" />
                <h4 style="margin-top:10px;">PRICE '.$l.'</h4>
                <input class="divtop" name="price'.$l.$count.'" step="0.01" type="number" value="'.${'prize'.$l}.'"  style="width:55px; text-align:center;" />
            </div>';
        }

And then when I get the $_POST I am checking if the input is 0 or “” and setting it to NULL.

for($z = 1; $z <= 6; $z++){
    ${'qty'.$z} = $_POST["qty".$z.$i];
    ${'price'.$z} = $_POST["timi".$z.$i]; 
    if( ${'timi'.$z} == 0 || ${'timi'.$z} == ""){ ${'timi'.$z} = NULL; }
    if( ${'qty'.$z} == 0 || ${'qty'.$z} == ""){ ${'qty'.$z} = NULL; }
}

And I am adding to the DB with this

$priceupdate = $conn ->query("UPDATE table SET qty1 = '$qty1',  qty2 = '$qty2',  qty3 = '$qty3',  qty4 = '$qty4', qty5 = '$qty5',  qty6 = '$qty6' WHERE id = '$id'"); 

But when the query runs, qty6 (for example) that is 0 or “” doesn’t insert as NULL in the DB but as 0, the table field is int (though it doesn’t really matter). Any ideas how to fix this? I am kinda stuck! enter image description here

I have tried (qty6 = $var) the query just stops there.

The structure does allow NULL as the default value is in fact NULL.

If I try ${‘qty’.$z} = ‘NULL’ ; this makes NULL a string so it wouldn’t help as the field value type for price is Float and for qty is Integer

Advertisement

Answer

Ok I figured it out, instead of using

$priceupdate = $conn ->query("UPDATE table SET qty1 = '$qty1',  qty2 = '$qty2',  qty3 = '$qty3',  qty4 = '$qty4', qty5 = '$qty5',  qty6 = '$qty6' WHERE id = '$id'"); 
if($priceupdate ->execute()){ do something }

I used with prepare like this

 $priceupdate = $conn ->query("UPDATE table SET qty1 = ?,  qty2 = ?,  qty3 = ?,  qty4 = ?, qty5 = ?,  qty6 = ? WHERE id = ?");
$a = $priceupdate->execute(array($qty1, $qty2, ..., $id));

And it seems to be working, this way NULL doesn’t become a string for sure.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement