Inserting instances of array into table using a for loop - php

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.

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.

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.

Related

Insert into table from array positions

I have a couple of arrays of values. I would like to insert them into a table one row at a time using a loop. I am able to insert the correct number of rows, but the values are not inserting properly.
For example, $ingredient_general is an array that has posted to this page. Assume it has 3 values. I want the value at position 0 to insert first, then on the next loop at position 1, and then then next row gets the value at position 2. Each of the three top variables are all arrays with the same number of values in each.
I tried doing $ingredient_general['.$i.'] in values part of the query in the loop but all it did was put "$ingredient_general[0]" into the table and not the value that this represents.
$ingredient_general = $_POST['ingredient_general'];
$ingredient_amount = $_POST['ingredient_amount'];
$ingredient_image = $_POST['ingredient_image'];
$recipe_ID = $_POST['recipe_ID'];
print_r($ingredient_general);
//$name = $ingredient_general.$ingredient_amount;
$c = count($ingredient_general);
for ($i = 0; $i <= $c; $i++) {
$addIngredientQuery = "INSERT INTO `ingredients` (recipe_ID,general_name, image) VALUES ('$recipe_ID', '$ingredient_general', '$ingredient_image')";
mysqli_query($con, $addIngredientQuery);
$i++;
}
You don't need to add single quotes around $i.
$addIngredientQuery = "INSERT INTO `ingredients`(recipe_ID, general_name, image) VALUES ('$recipe_ID','$ingredient_general[$i]', '$ingredient_image')";
For best practice, I would wrap your array with curly brackets, if you don't want to escape your string and concatenate it.
$addIngredientQuery = "INSERT INTO `ingredients`(recipe_ID, general_name, image) VALUES ('$recipe_ID','{$ingredient_general[$i]}', '$ingredient_image')";
Additional:
You are increasing $i twice. Once in the loop and once within the loop. You also want to run the loop while $i < $c instead of $i <= $c since the pointer starts at 0 and the count starts at 1.
<?php
$ingredient_general = array('test', 'testing', 'tester');
$ingredient_amount = 5;
$ingredient_image = 'image.jpg';
$recipe_ID = 2;
$c = count($ingredient_general);
for($i = 0; $i < $c; $i++) {
$addIngredientQuery = "INSERT INTO `ingredients`(recipe_ID, general_name, image) VALUES ('$recipe_ID','{$ingredient_general[$i]}', '$ingredient_image')";
echo $addIngredientQuery . PHP_EOL;
}
?>
Using the second method suggested, here was my output:
INSERT INTO ingredients(recipe_ID, general_name, image) VALUES
('2','test', 'image.jpg') INSERT INTO ingredients(recipe_ID,
general_name, image) VALUES ('2','testing', 'image.jpg') INSERT INTO
ingredients(recipe_ID, general_name, image) VALUES ('2','tester',
'image.jpg')
This is the complex (curly) syntax for string interpolation.

How to refer to a variable dynamically [duplicate]

I have multiple PHP variables in the form
$number1, $number2, $number3 and so on...
I would like to dynamically reference these inside of a loop to retrieve information from them, but am not sure how to reference the static variable dynamically. Ex:
for($i = 1; $i <= 10; $i++) {
//The first number to be printed should be the value from
//$number1 not $number concatenated to $i
//here are some of the strings I tried:
echo "$number$i";
echo "{$number}$i";
echo "{$number}{$i}";
}
This should do it:
echo ${"number{$i}"};
But why not use arrays instead? Having $number[$i] is much more readable...

PHP - for loops through associative array

I have an associative array $_POST, which has 3 key value pairs (There are other key value pairs which I am not interested in).
$_POST[Var1]
$_POST[Var2]
$_POST[Var3]
How do I use a for loop to loop through and echo the values in each?
for ($i = 1; $i <= 3; $i++){
echo $_POST['Var' . '$i'];
}
This does not seem to work.
Get rid of the single quotes around $i as that makes it a literal string and your variable is not interpolated:
for ($i = 1; $i <= 3; $i++){
echo $_POST['Var' . $i];
}
This is basic PHP. I strongly recommend reading the manual to learn more about the fundamentals of PHP.
Check this. While using php varibles dont put upper commas for the variables.
<?php
$_POST["file1"];
$_POST["file2"];
$_POST["file3"];
for ($i = 1; $i <= 3; $i++){
echo $_POST['file'.$i];
}
Or this way:
$_POST["Var{$i}"];

PHP dynamically reference variable in string literal

I have multiple PHP variables in the form
$number1, $number2, $number3 and so on...
I would like to dynamically reference these inside of a loop to retrieve information from them, but am not sure how to reference the static variable dynamically. Ex:
for($i = 1; $i <= 10; $i++) {
//The first number to be printed should be the value from
//$number1 not $number concatenated to $i
//here are some of the strings I tried:
echo "$number$i";
echo "{$number}$i";
echo "{$number}{$i}";
}
This should do it:
echo ${"number{$i}"};
But why not use arrays instead? Having $number[$i] is much more readable...

PHP: How to loop through properties with sequential names

If I have a table with columns called image1, image2, image3, etc and I pulled those in an object-oriented manner, like this:
$images->image1
$images->image2
$images->image3
etc.
Is there any way to process these in a loop? Something like:
for (i=1; i<count($images); $i++) {
$array[$i] = $images->image?
}
I realize the above won't work, but was wondering if someone could tell me a way that will work. Thanks.
Pulling them from the DB in an array might be a better option, but you can do it with objects by using variable variables:
for ($i = 1; i < $length; $i++) {
$array[] = $images->{'image' . $i};
}
You should use an array instead.
However, you can also use variable variables for this madder.
for ($i = 1; i < $len; $i++) {
$array[] = $images->{'image' + $i};
}

Categories