Kevin Kevin - 8 days ago 5
HTML Question

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++;
}

Answer

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.