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); 
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doubo1711 2014-03-18 01:16

    If this is your query:

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

    Then you have a problem with single quotes. You probably want:

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

    or

    INSERT INTO todo(one, two, three) VALUES (val1, val2, val3);
    
    评论
    解决 无用
    打赏 举报
  • douchui4815 2014-03-18 01:20

    Can you please elaborate more what you want for your output? And input?

          if(empty($one_input) || empty($two_input) || empty($three_input)){
    
          /* Do Nothing */
    
          }
    
          else {
    
          query str="INSERT INTO todo('','','') VALUES ('','','')";
    
          }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题