1

Possible Duplicate:
Able to see a variable in print_r()'s output, but not sure how to access it in code

Can I store an array in a variable?

I have this array:

$_POST['product']

and when I print it:

echo "<PRE>";
print_r($_POST['product']);
echo "</PRE>";

the result is:

<PRE>Array
(
    [0] => Array
        (
            [0] => 1
            [1] => cola
            [2] => wwww
            [3] => 1
            [4] => 2.00
            [5] => 0.00
            [6] => 2.00

        )

)
</PRE>

How can I store the value of the array in a variable? For example, I need to insert [1] => cola into the table in the database.

Community
  • 1
  • 1

4 Answers4

1

You must use a foreach loop to "scan" the array and send an INSERT query to your database, like this :

<?php
$updateStmt = $pdo->prepare("INSERT INTO table (field) VALUES (:FIELD)");
foreach( $_POST['product'] as $key => $val ){
    $updateStmt->execute(array(
        ':FIELD' => $val
    ));
}
?>
Vince
  • 3,274
  • 2
  • 26
  • 28
0
if(!empty($_POST['product'])) {
    $colaVar = $_POST['product'][0][1];
    echo $colaVar; // outputs'cola'
}
Havelock
  • 6,913
  • 4
  • 34
  • 42
lostsource
  • 21,070
  • 8
  • 66
  • 88
0

You don't need that at all, just do the following:

$arr = $_POST['product']
echo $arr[0][1]

This is the normal way to access arrays values to do anything you want.

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
0

You can access the array like $_POST['product'][0][1] to get the value of cola.

For multiple inserting to database you should use foreach loop or for loop.

UPDATED

Alright, Foreach Loop

foreach($_POST['product'] as $product) {
   mysql_query("INSERT INTO YOURTABLENAME('FIELD1','FIELD2'....) VALUES('".$product[0]."','".$product[1]."'....)"); 

}

I prefered to use for loop .

$count_array = count($_POST['product']);
for($i=0; $i>= $count_array; $i++){
   mysql_query("INSERT INTO YOURTABLENAME('FIELD1','FIELD2'....) VALUES('".$_POST['product'][$i]."','".$_POST['product'][$i]."'....)"); 
}

THere is also an optimize way for inserting in the database by avoiding the insert sql inside the for/foreach loop.. But for now that should work for you.. :)

Anthony Pillos
  • 195
  • 4
  • 12
  • *Remember to sanitize your inputs!!!1!11one* Use `mysql_real_escape_string()`, PDO, or some other method. – Andrew M Nov 11 '12 at 06:53