Thursday, May 1, 2014

How to insert 3 or multiple arrays into 1 or 2 MySql tables

After googling for 2 days, Here is how to add multi-arrays into MySQL tables

Example we have 3 arrays:

$item= array(1, 2, 3, 4, 5);
$fruit= array('apple', 'banana', 'ananas', 'orange', 'lemon');
$price= array(32, 54, 26, 97, 47);

foreach($fruit as $key => $fruitName)
    {
    $query = " INSERT INTO fruits (item, fruit)
               VALUES ('$item[$key]', '$fruit[$key]')";
    mysql_query($query) or exit(mysql_error());
    $query = " INSERT INTO prices (item, price)
               VALUES ('$item[$key]', '$price[$key]')";
    mysql_query($query) or exit(mysql_error());
    }
This code is working as charm ! Enjoy.

No comments:

Post a Comment