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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试