doudong4532 2018-10-16 23:45
浏览 81
已采纳

将php变量保存为sql的null

I have made a program to read 3 inputs on another page, the ID, code1, and code2.

One is a code to have easy to search, while the other 2 are variables that will be used to sum, subtract, multiply an divide and then save it all in a database

I have connected it to this php code:

if (isset($_POST["ID"]))
 {
    $id=($_POST["ID"]);
   $val1=($_POST["code1"]);
   $val2=($_POST["code2"]);

if ($val2 == 0){
    $sum = $val1 + $val2;
    $res = $val1 - $val2;
    $mul = $val1 * $val2;
    $div = NULL;
}else{
    $sum = $val1 + $val2;
    $res = $val1 - $val2;
    $mul = $val1 * $val2;
    $div = $val1 / $val2;
}

 $cnn=mysqli_connect("localhost","root","CC2CRO","ejercicios");
 if ($cnn) {
echo ("<SCRIPT LANGUAGE='JavaScript'>window.alert('CONEXION EXITOSA  
 !!!!')</SCRIPT>");         
    $sqlnr = mysqli_query($cnn, "INSERT INTO calculadora (Id, Valor1, 
 Valor2, Suma, Resta, Multiplicacion, Division) VALUES ('$id', '$val1', 
 '$val2', '$sum', '$res', '$mul', '$div')");

That is connected to MySQL database, so far it has worked, like for example I put OP45, 12, 3 when I see my database is saved as OP45 12 3 15 9 36 4 my issue is with when I use 0 for $val2, I wanted to save it as null since you can´t divide by 0, but when I run it it leaves the whole row empty, only does that when $val2 is 0, if $val2 is 1 or more it fills the entire row.

On my database Id is varchar and the rest are decimal (6,2), Id is PK and Not Null, also Valor1 and Valor2 are Not Null too.

below the code block from above I have this other one

 if ($sqlnr)
        echo ("<SCRIPT LANGUAGE='JavaScript'>window.alert('REGISTRO ALMACENADO CORRECTAMENTE !!!!')</SCRIPT>");
    else{
        echo ("<SCRIPT LANGUAGE='JavaScript'>window.alert('EL REGISTRO NO PUDO SER GUARDADO !!!!')</SCRIPT>");
    }

The first one is seen if it was saved in the database and the second one if it wasn't saved, so when val2 is 0 it always gives me the 2nd message.

展开全部

  • 写回答

1条回答 默认 最新

  • douling0053 2018-10-17 00:38
    关注

    You should change

    $div = NULL;  to  $div = 'NULL';
    

    then remove single quotes in '$div' in sql string ( '$div' to $div )

    $sqlnr = mysqli_query($cnn, "INSERT INTO calculadora (Id, Valor1, 
            Valor2, Suma, Resta, Multiplicacion, Division) VALUES ('$id', '$val1', 
           '$val2', '$sum', '$res', '$mul', $div)");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部