【问题标题】:How to insert 3 arrays into 2 MySql tables?如何将 3 个数组插入 2 个 MySql 表?
【发布时间】:2011-06-10 13:33:01
【问题描述】:

我有 3 个具有相同项目数的简单数组

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

我有两个 MySql 表。第一个表“fruits”包含行“id”和“name”,第二个表“prices”包含行“fruit”和“price”。

在表“fruits”中,我需要从数组 $id 和 $fruit 中插入项目。如果没有具有相同 ID 号的行,来自 $id 的项目应该进入行“id”,来自 $fruit 的项目应该进入行“name”。我还需要将数组 $id 和 $price 中的所有项目插入到表“价格”中。与上表相同,数组 $id 中的项目应放入“fruit”行,数组 $price 中的项目应放入“price”行。

感谢您的帮助。

【问题讨论】:

  • 请不要使用这样的字符串(applebanana),这是一种非常糟糕的做法。使用'apple''banana'

标签: php mysql arrays foreach insert-update


【解决方案1】:
$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
    }

但是请不要让我在这里验证输入 [是否存在键等] - 这是快速的 sn-p 可能会有所帮助。 ;]

顺便说一句。如果你有一张桌子的水果(id,name,price)会好得多。 ;]

【讨论】:

    【解决方案2】:

    使用array_combine() 创建两个新数组:

    • $id$fruit 的组合
    • 结合$id$price

    遍历这两个关联数组中的每一个,并插入您的记录。

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多