doudong4532 2018-10-17 07: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 08: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)");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line