0

i want to insert the values of two arrays into a table in a single query . Is it possible to do something like that.

table format

id | product_id | category_id | blog_id | updated_by | created_date 

category _id

Array
(
    [0] => 4
    [1] => 15
    [2] => 18
)

Product_id

Array
(
    [0] => 2260 
    [1] => 1401 
)

Blog id = mysql_insert_id();

result

id | product_id | category_id | blog_id | updated_by  
 1      2260        4               15      xyz         
 2      1401        15              15      xyz   
 3      null        18              15      xyz

Any suggestions for me also to improve the better insert query for this.

2
  • what you have tried? how u r doing this right now? Commented Jul 3, 2012 at 6:05
  • i have tried writing insert queries into the two times for two arrays Commented Jul 3, 2012 at 6:30

3 Answers 3

2
INSERT INTO `Table_Name` (`product_id`, `category_id`, `blog_id`, `updated_by`) VALUES (2260, 4, 15, 'xyz'), (1401, 15, 15, 'xyz'), (, 18, 15, 'xyz');

I assumed that id column is an auto incremented one.

Sign up to request clarification or add additional context in comments.

1 Comment

@Ragavendran Ramesh: Its good, you need to append the query values by iterating your both arrays.
0

You can insert multiple rows at one go in the same query that you are using now. Just add a comma, and put in more values:

Insert into myTable values ('field1-var1','field2-var2'), ('field1-var2','field2-var2') ..

Comments

0
$combain = array_merge($cat , $proid);   
for($i = 0; $i <count($combain); $i++ )
            {
                if(isset($proid[$i])) {
                    $product_id = $proid[$i];
                }
                else{
                    $product_id = "''";
                }            
                if(isset($cat[$i])){
                    $category_id = $cat[$i];
                }
                else{
                    $category_id = "''";
                }   
                if(!empty($cat[$i]) || !empty($proid[$i])) {

                    @$values[] ="('',". $blogid.",".$category_id.",".$product_id.","."'".$updated_by."'".",now())";
                }
            }        
            $query = $this->db->query("insert into blog_details (id , blog_id , cat_id, pro_id, updated_by , created_date) values" . implode(',', $values));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.