【问题标题】:How to insert into database 3 arrays如何插入数据库3个数组
【发布时间】:2011-10-13 22:31:39
【问题描述】:

我想使用“foreach”或其他方法将 3 个数组插入数据库

sql:

CREATE TABLE IF NOT EXISTS `orders` (
  `id` int(11) NOT NULL auto_increment,
  `order` text NOT NULL,
  `price` text NOT NULL,
  `quantity` text NOT NULL,
   PRIMARY KEY  (`id`)
   ) ENGINE=MyISAM DEFAULT CHARSET=cp1256 AUTO_INCREMENT=1 ;

表格:

<form method="POST" action="#">
    <p dir="ltr"><input type="text" name="order[]" size="20"></p>
    <p dir="ltr"><input type="text" name="price[]" size="20"></p>
    <p dir="ltr"><input type="text" name="quantity[]" size="20"></p>
    <p dir="ltr"><br /></p>
    <p dir="ltr"><input type="submit" value="Submit" name="B1"></p>
</form>

对于我使用的 2 个数组:

foreach (array_combine($orders, $prices) as $order=> $price) {

}

我想这样插入它: 例如:

1-订单-价格-数量

2-订单-价格-数量

3-订单-价格-数量

4-订单-价格-数量

5-订单-价格-数量

...

...

如何编辑此代码以插入 3 个数组

谢谢

【问题讨论】:

    标签: arrays insert foreach


    【解决方案1】:

    下面的代码显示了如何做到这一点,但我不确定您的表单是否真的返回数组。您也应该进行一些输入检查,以查看这些值是否确实是数组,并且是否都具有相同数量的项目(count 函数)。

    下面的代码只是创建了一个基于三个数组的插入语句。

    // Get the arrays and sanatize them. I use hard codes ones in this example.
    $orders = array('a', 'b', 'c', 'd', 'e');
    $prices = array(1, 2, 3, 4, 5);
    $quantities = array(5, 6, 7, 8, 9);
    
    
    $query = "INSERT INTO orders (order, price, quantity) VALUES";
    $comma = "";
    
    // Move the array cursor of all arrays to the beginning.
    reset($prices);
    reset($quantities);
    foreach ($orders as $order)
    {
        // Get values and sanatize.
        $order = mysql_real_escape_string($order);
        $price = (float)current($prices);
        $quantity = (int)current($quantities);
    
        // Add to query.
        $query .= "$comma\n('$order', $price, $quantity)";
        $comma = ",\n";
    
        // Move pointer (for $orders, the foreach does this).
        next($prices);
        next($quantities);
    }
    
    // Execute $query.
    var_dump($query);
    

    【讨论】:

    • 我看到了您的编辑,但这就是这段代码的作用,不是吗?当然,您仍然应该执行查询等..
    • 我使用了你的代码,它运行良好,但我不明白为什么代码不插入数据库,这部分 var_dump($query);打印每件事都可以
    • 哦,是的,我刚刚打印了查询,但您实际上需要通过调用 mysql_execute 或您正在使用的任何数据库库来执行它。我相信您至少对使用 MySQL 和 PHP 有所了解?既然你问了这么一个具体的问题,我以为你知道基础知识。如果您确实执行了查询并且没有任何反应,请使用mysql_error 或类似的函数来获取最后一个错误。生成的查询中可能存在拼写错误。
    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    相关资源
    最近更新 更多