开发者

How to insert 3 arrays into 2 MySql tables?

I have 3 simple arrays with same number of items

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

I have two MySql tables. First table 'fruits' which contain rows 'id' and 'name' and second table 'prices' which contain rows 'fruit' and 'price'.

In table 'fruits' I need to insert items from arrays $id and $fruit. Items from $id should go into row 'id' and items from $fruit should god into row 'name' IF there is not a row with same id number. Also I need to开发者_如何学C insert all items from arrays $id an $price into table 'prices'. Same like in a previous table, items from array $id should be placed into row 'fruit' and items from array $price should be placed into row 'price'.

Thank you for helping.


$id= 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 (id, name)
        VALUES ('.$id[$key].', '.$fruit[$key].')
        ';
    // execute
    $query = '
        INSERT INTO prices (id, price)
        VALUES ('.$id[$key].', '.$price[$key].')
        ';
    // execute
    }

But please don't ask me to validate input [existence of keys, etc] here - this is quick snippet that probably will help. ;]

BTW. It would be much better if you'd have one table fruits(id, name, price). ;]


Use array_combine() to create two new arrays:

  • one combining $id with $fruit
  • one combining $id with $price

Loop through each of these two associative arrays, and insert your records.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜