doumao1519 2014-03-18 01:10
浏览 35
已采纳

仅当输入文本不为空时才插入到mysql中 - Codeigniter

I m trying to insert some data into a table but I want to only insert if the variable is not empty.

My model code below.

$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);

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 '' at line 1

INSERT INTO todo (one, two, three) VALUES ('val1, val2, val3);',

  • 写回答

3条回答 默认 最新

  • dongxing2302 2014-03-18 01:24
    关注

    I would use following syntax in your situation:

    INSERT INTO todo
    SET
        one='val1',
        two='val2',
        three='val3'
    

    You can set field=value pairs in an array easier and add to the statement by imploding.

    Added sample below:

            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); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,