我正在尝试将一些数据插入表中,但是我只想在变量不为空的情况下插入。

我的模型代码如下。

$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行的''附近使用正确的语法

插入待办事项(1、2、3)值('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/

10-11 22:22
查看更多