dongyutan1703 2014-05-22 13:51
浏览 186
已采纳

PHP为数据库插入设置了默认值

I have a number box <input type='number' step='any' name='number' id='number'>

and I take that value and call it in a function like so:

insertIntoDB($number)

function insertIntoDB($number = null){

  //insert into db
  "INSERT INTO 'tablename' (number) VALUES " . $number;

}

and I get this error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '

Is there away so if the user leaves the field blank it will enter the value as null?

  • 写回答

1条回答 默认 最新

  • douban2014 2014-05-22 13:53
    关注

    You can set default values when creating the table itself, but apart from that, the code you pasted is missing some brackets:

    INSERT INTO `tablename` (number) VALUES (" . $number.")";
    

    If you want to use a NULL when inserting and get a default value in the table, you can do it when creating the table like this:

    CREATE TABLE test 
        (
        id INT NOT NULL AUTO_INCREMENT, 
        someField VARCHAR(15) NOT NULL DEFAULT 'on'
        )
    

    Now when you try to insert data into it, you can do the following:

    insert into `tablename` (id, someField) values (null, null)
    

    and get a row with an incremented ID and the string 'on' in the column someField.

    If you want to check for nulls when inserting data into a table, you can then use something like the following to ensure you have the value:

    $someField=(isset($number))?$number:'null';
    INSERT INTO `tablename` (number) VALUES (" . $someField.")";
    

    This is assuming you have already verified that $number is either numeric or isn't submitted when sending the form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作