我试图插入一些数据到一个表,但我想只插入,如果变量不是空的。
我的模型代码如下。
$query_str = "INSERT INTO todo (";
$query_and=array();
if( !empty($one_input)){
$query_and[]= 'one';
}
if( !empty($two_input)){
$query_and[]= 'two';
}
if( !empty($three_input)){
$query_and[]= 'three';
}
$query_str .= implode(', ', $query_and);
$query_str .= ') VALUES (?, ?, ?)';
$query_data=array();
if( !empty($one_input)){
$query_data[]= $one_input;
}
if( !empty($two_input)){
$query_data[]= $two_input;
}
if( !empty($three_input)){
$query_data[]= $three_input;
}
$query_dat = implode(', ', $query_data);
$query_dat .= ");";
$q = $this->db->query($query_str, $query_dat);
你的SQL语法有错误;查看与MySQL服务器版本对应的手册,了解在"at line 1
"附近使用的正确语法。INSERT INTO todo (1,2,3) VALUES ('val1, val2, val3);',
在你的情况下我会使用以下语法:
INSERT INTO todo
SET
one='val1',
two='val2',
three='val3'
您可以更容易地在数组中设置字段=值对,并通过内爆添加到语句中。
添加如下示例:
if( !empty($one_input)){
$query_data[]= "one='$one_input'";
}
if( !empty($two_input)){
$query_data[]= "two='$two_input'";
}
if( !empty($three_input)){
$query_data[]= "three='$three_input'";
}
$query = "INSERT INTO todo SET " . implode(",", $query_data);
如果这是您的查询:
INSERT INTO todo(one, two, three) VALUES ('val1, val2, val3);'
那么单引号就有问题了。您可能需要:
INSERT INTO todo(one, two, three) VALUES ('val1', 'val2', 'val3');
或
INSERT INTO todo(one, two, three) VALUES (val1, val2, val3);
你能详细说明你想要什么样的输出吗?和输入?
if(empty($one_input) || empty($two_input) || empty($three_input)){
/* Do Nothing */
}
else {
query str="INSERT INTO todo('','','') VALUES ('','','')";
}