我正在尝试将一些数据插入表中,但我只想在变量不为空时插入。
下面是我的模型代码。
$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 服务器版本相对应的手册,了解在第 1 行 '' 附近使用的正确语法
INSERT INTO todo (一、二、三) VALUES ('val1, val2, val3);',
最佳答案
我会在您的情况下使用以下语法:
INSERT INTO todo
SET
one='val1',
two='val2',
three='val3'
您可以更轻松地在数组中设置 field=value 对,并通过内爆添加到语句中。
添加了以下示例:
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);
关于php - 仅当输入文本不为空时才插入 mysql - Codeigniter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22468571/