PHP/MySql - Inserting Multiple Records

Discussion in 'PHP' started by cancer10, Mar 20, 2008.

  1. #1
    I want to insert records into multiple tables at one go, I am doing this in the following way, is this the correct way of doing? If not, what is the better way?



    
    mysql_query("insert into table1 values('abc')");
    mysql_query("insert into table2 values('ttt')");
    mysql_query("insert into table3 values('5t6')");
    mysql_query("insert into table4 values('ghy')");
    mysql_query("insert into table5 values('gfd')");
    
    Code (markup):


    Please help


    Thanx
     
    cancer10, Mar 20, 2008 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Depending on your version, you may also be able to do:

    
    
    mysql_query("insert into table1 values('abc');insert into table2 values('ttt');insert into table3 values('5t6');insert into table4 values('ghy');insert into table5 values('gfd')");
    
    
    PHP:
    Also if you can use the mysqli class, you can run a bunch of inserts as a single transaction:

    
    $db->autocommit(FALSE);
    
    $db->query("INSERT INTO table VALUES (blah, blah, blah)");
    $db->query("INSERT INTO table VALUES (blah, blah, blah)");
    $db->query("INSERT INTO table VALUES (blah, blah, blah)");
    $db->query("INSERT INTO table VALUES (blah, blah, blah)");
    $db->query("INSERT INTO table VALUES (blah, blah, blah)");
    $db->query("INSERT INTO table VALUES (blah, blah, blah)");
    
    $db->commit();
    
    PHP:
     
    jestep, Mar 20, 2008 IP
  3. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #3
    I do it that way. However if these inserts will be done very often then you might have to look into different ways because it could slow down the server.

     
    stephan2307, Mar 20, 2008 IP