kasunjith kasunjith - 1 year ago 81
PHP Question

How to do a foreach within INSERT?

When I enter data to mysql it shows as below image, I want to take all the data to a one row, not in many rows as below image. but since I'm entering data using an array I only have access to one element at once. So how can I enter data to a single line? below is a snip of my code and a snip from my table , thank you very much.

$array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");

foreach ($array as $s) {
$amount=//some value from $_POST
$value=//some value from $_POST

$sql = "INSERT INTO portfolio ({$s} , {$sss}) VALUES ('{$amount}', '{$value}')";

Snip from MYSQL table
enter image description here

Answer Source

You can first add those "PR.." columns to your array and then use implode() to build your into-clause.

$array = array("AAPL","GOOG","YHOO","FB","MSFT","NKE","SBUX");
$amount = 'dunno';
$value = 'something';
foreach ($array as $s) {
    $array[] = "PR" . $s;
$sql = 'INSERT INTO portfolio (' . implode(',', $array) . ') 
            VALUES ("' .$amount . '", "' . $value . '")';

Can't build the coomplete query though because you didn't specify what kind of data $amount and $value are.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download