Reputation: 4028
I am trying to insert rows of data in an array into a table. It's inserting this instead of the actual data:
Here is my code:
for ($i = 0; $i < $arraycount; $i++)
{
$db->query("INSERT INTO contact_tariffs (qid, retail_name, tariff_name, tariff_net, tariff_rental, tariff_inclusive, tariff_length, tariff_data)
Values ('$qid', '$quote->retail_name[$i]', '$quote->tariff_name[$i]', '$quote->tariff_net[$i]', '$quote->tariff_rental[$i]', '$quote->tariff_inclusive[$i]', '$quote->tariff_length[$i]', '$quote->tariff_data[$i]' )");
}
I have had similar problems when using $_POST
and $_SESSION
variables and the only solution I had for that was to temporarily transport the values into temp variables and use the temp variables to insert into the database.
Upvotes: 0
Views: 336
Reputation: 33153
The variables are too complex to use inside a string. PHP interprets $quote->retail_name
as one variable and $i
another, because it doesn't know where one variable ends and where the other starts. For example:
$i = 1;
$quote->retail_name[ 1 ] = 'foo';
echo "result: $quote->retail_name[$i]"; // --> result: Array[1]
// the above is the same as
// echo $quote->retail_name; echo "["; echo $i; echo "];
echo "result: ".$quote->retail_name[$i]; // --> result: foo
// The above leaves the variable outside the string so it's parsed correctly.
// You could also use "result: {$quote->retail_name[$i]}"
See also http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
Try this instead:
for ($i = 0; $i < $arraycount; $i++)
{
$db->query("INSERT INTO contact_tariffs (qid, retail_name, tariff_name, tariff_net, tariff_rental, tariff_inclusive, tariff_length, tariff_data)
Values ('$qid', '".$quote->retail_name[$i]."', '".$quote->tariff_name[$i]."', '".$quote->tariff_net[$i]."', '".$quote->tariff_rental[$i]."', '".$quote->tariff_inclusive[$i]."', '".$quote->tariff_length[$i]."', '".$quote->tariff_data[$i]."' )");
}
Although you should escape the values as well. Something like PDO would be preferable.
Upvotes: 2
Reputation: 3679
You can use curly brackets, to insert array values directly into a double quoted string:
for ($i = 0; $i < $arraycount; $i++)
{
$db->query("INSERT INTO contact_tariffs (qid, retail_name, tariff_name, tariff_net, tariff_rental, tariff_inclusive, tariff_length, tariff_data)
Values ('{$qid}', '{$quote->retail_name[$i]}', '{$quote->tariff_name[$i]}', '{$quote->tariff_net[$i]}', '{$quote->tariff_rental[$i]}', '{$quote->tariff_inclusive[$i]}', '{$quote->tariff_length[$i]}', '{$quote->tariff_data[$i]}' )");
}
...and please be aware of SQL injections.
Upvotes: 1