我有一个号码框<input type='number' step='any' name='number' id='number'>
我获取该值并在函数中调用它,如下所示:
insertIntoDB($number)
function insertIntoDB($number = null){
//insert into db
"INSERT INTO 'tablename' (number) VALUES " . $number;
}
我收到此错误:
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 ' '
如果用户将该字段留空,是否会输入空值?
最佳答案
您可以在创建表本身时设置默认值,但除此之外,您粘贴的代码缺少一些括号:
INSERT INTO `tablename` (number) VALUES (" . $number.")";
如果你想在插入时使用NULL并在表中获取默认值,你可以在创建表时这样做:
CREATE TABLE test
(
id INT NOT NULL AUTO_INCREMENT,
someField VARCHAR(15) NOT NULL DEFAULT 'on'
)
现在,当您尝试向其中插入数据时,您可以执行以下操作:
insert into `tablename` (id, someField) values (null, null)
并在 someField
列中获取 ID 递增且字符串“on”的行。
如果您想在向表中插入数据时检查空值,则可以使用类似以下内容来确保您拥有该值:
$someField=(isset($number))?$number:'null';
INSERT INTO `tablename` (number) VALUES (" . $someField.")";
假设您已经验证 $number 是数字或者在发送表单时未提交。
关于PHP为数据库插入设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23808828/