insert query using foreach loop receiving Uncaught Error: Call to a member function execute() on boolean

后端 未结 2 929
一个人的身影
一个人的身影 2021-01-29 07:44

I am trying to insert multiple rows at once to my db, I posted a question here the other day see here. Regarding my insert query only insert one row into the db, even if it was

相关标签:
2条回答
  • 2021-01-29 08:05

    Your SQL is generated incorrectly: INSERT INTO ord_dets(Order_ID,custmer_ip,Resturant_ID,Resturant_name,City_name, Product_Id,Product_Name,Product_Price,item_sub) VALUES (...,...,....)(...,...,....)(...,...,....)(...,...,....)(...,...,....)

    This is how it looks like. Fix it ad there will be no error

    Solution here is to add commas betweeen values: VALUES (...,...,....),(...,...,....),(...,...,....),(...,...,....),(...,...,....)

    UPD: Actually I can't see where you add $query_parts to your query string

    UPD2: this is how it should look to avoid sql injections:

    $_query = "INSERT INTO ord_dets(Order_ID,custmer_ip,Resturant_ID,Resturant_name,City_name, Product_Id,Product_Name,Product_Price,item_sub) VALUES (?,?,?,?,?,?,?,?,?)";
    $stmt = $dbc->prepare($_query);
    
    for($x=0;$x<count($OI); $x++){
        if (!$query_run->execute([$OI[$x] , $ip[$x], $_SESSION['rest_id'][$x] ,
              $rest_name[$x] , $City_name[$x] , $Product_Id[$x] ,
              $product_name[$x] , $prod_price[$x] ,$item_sub[$x]])) )
        {
            insertError = "There was an error inserting data: " . $query_run->error; 
              print "affected rows:" . $query_run->affected_rows;
        }
    }     
    
    0 讨论(0)
  • 2021-01-29 08:07

    change it like this to separated it with coma.

    $_query = "INSERT INTO ord_dets(Order_ID,custmer_ip,Resturant_ID,Resturant_name,City_name,
            Product_Id,Product_Name,Product_Price,item_sub) 
    VALUES ";
            $_query_parts  = array();
            $sep ="";
            for($x=0;$x<count($OI); $x++){
            $_query_parts  = "$sep('" . $OI[$x] . "', '" . $ip[$x] . "','" . $_SESSION['rest_id'][$x] . "','" . $rest_name[$x] . "',
                '" . $City_name[$x] . "','" . $Product_Id[$x] . "','" . $product_name[$x] . "','" . $prod_price[$x] . "','" . $item_sub[$x] . "')";
            $sep=",";
            }
          $query_run = $dbc->prepare($_query);
           echo $_query;
    
            if (!$query_run->execute()) {
                $insertError = "There was an error inserting data: " . $query_run->error;
          print "affected rows:" . $query_run->affected_rows; //how many records affected?         
    
        }
      }
    
    0 讨论(0)
提交回复
热议问题