0

I found this type of question on stack overflow and other website but none of the solution work in my project.

I am working in Lumen Laravel micro-framework for API and I want to insert multiple record with single query.

below is the code for single record insert and working fine.This code is for follow category by user. So when user click on Follow Category button this query is run and insert one record in database with user_id and category_id field.

 public function insertUserFollow($category){

    $sql = " INSERT INTO news_user_category_following
             SET
              user_id = :user_id,
              category_id = :category_id
            ";
    $sth = $this->connection->prepare($sql);

    $sth->bindParam(":user_id", $category['user_id']);
    $sth->bindParam(":category_id", $category['category_id']);

    $status  = $sth->execute();

    if(TRUE == $status){
        return $status;
    }else{
        return FALSE;
    }

}

Using above code my database looks like this :

user_id | category_id

 ------ | ------

    1   |   5

Now How I want to insert is below :

user_id | category_id

 ------ | ------

    1   |   5
    1   |   2
    1   |   3
    1   |   6
    1   |   4
    1   |   1

So, I want multiple record to be inserted by single query and all data are coming dynamic so how can I manage for each look in query.

Vatev
  • 7,493
  • 1
  • 32
  • 39
Dhaval
  • 1,393
  • 5
  • 29
  • 55
  • I'm voting to close this question as off-topic because if you are inserting only a few records, this is a huge waste of effort. If you are inserting a lot of data, there are lots of other more efficient ways such as LOAD DATA INFILE rather than generating queries in PHP. – e4c5 Nov 29 '16 at 12:11
  • @e4c5 I want to insert more than one record and it's not specify that it will be 5 or 10 records. it will be depend on user input. And I want to done this with PDO query – Dhaval Nov 29 '16 at 12:15
  • What have you already tried to achieve this? – Andre Nov 29 '16 at 12:18
  • @Andre I tried http://stackoverflow.com/questions/1176352/pdo-prepared-inserts-multiple-rows-in-single-query – Dhaval Nov 29 '16 at 12:19
  • 1
    you would have spent at least half an hour on this task by now. Once you complete it you will be able to save about 0.005 seconds per page load. – e4c5 Nov 29 '16 at 12:19

0 Answers0