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 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了