kasunjith kasunjith - 5 months ago 12
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) {
$sss="PR".$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

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 . '")';
echo $sql; // INSERT INTO portfolio (AAPL,GOOG,YHOO,FB,MSFT,NKE,SBUX,PRAAPL,PRGOOG,PRYHOO,PRFB,PRMSFT,PRNKE,PRSBUX) VALUES ("dunno", "something")
exit;

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

Comments