开发者

How to insert into database 3 arrays

i want to insert 3 arrays into database using "foreach" or something else

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 ;

fo开发者_JAVA百科rm :

<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>

For 2 arrays i use :

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

}

i want to insert it like that : ex:

1- order - price - quantity

2- order - price - quantity

3- order - price - quantity

4- order - price - quantity

5- order - price - quantity

...

...

how can i edit to this code to insert 3 arrays

Thank you


The code below shows how to do that, but I'm not sure if your form actually returns arrays. You should do some input checking too, to see if the values are indeed arrays, and do all have the same number of items (count function).

Code below just creates an insert statement based on three arrays.

// 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);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜