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.
Related
I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized
I wish to create a piece of dynamic SQL where the values from string variables are used as variables in the SQL string:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'1234');"
This works.
What I need to do however, is to have "variable variables"?
So earlier on in the code:
foreach($array as $val)
{
$s .= ',"$val"[$i]';
}
This creates the string:
s = ,'$val[0]','$val[1]'
When inserted as the SQL string:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,$s);"
It returns:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'$val[0]','$val[1]');"
Whereas it should return:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'12','34');"
This is being very literal as the MySQL insertion is on a loop where by $val is the array value and [0] is the key.
I'm not sure if this makes sense to anybody as I'm struggling to wrap my head around it, please let me know if my question is to vague or just doesn't make any sense at all.
Thanks
Nick
You are using single quotes, so no string interpolation is done, if you want strings interpolated you have to use double quotes"$var":
$arr = array( 1,2,3);
$i = 0;
echo '$arr[0]'; // prints: $arr[0] <== Your error is here
echo "$arr[0]"; // prints: 1
A better approach
Anyways, you may like to do it this way:
$array = array(12, 34);
$s = implode("', '", $array); // $s is: 12', '34
$s = ", '$s'"; // $s is: '12', '34'
echo $s; // prints: , '12', '34'
From what I could understand from your question, this might help you to achieve what you are looking for.
On your foreach loop you are using
$s .= ',"$val"[$i]';
$val is not concatenated in correct way
try this one
$s .= ','.$val[$i];
You can split values in array by , with implode function
For example:
$array[] = 12;
$array[] = 31;
implode(','$array) returns 12,31
so you could use $s = ','.implode(','$array); to achieve same result
Using your code I think this is what you are trying to do but as I said you are missing attributes.
$s="";
$array = array("12","34");
for($i =0; $i < count($array); $i++)
{
$s .= ",'" . $array[$i] . "'";
}
$sql = "INSERT INTO `product` (`id`,`number`) VALUES (NULL$s);";
I'm exploding a comma separated list into a variable named $tagArray and trying to write those values into incrementing rows of a table.
The code below works in so much as it creates the appropriate number of rows in my table but it only writes the first letter of the comma separating string (ie. if the string reads as "one, two, three", "o" is written in the first row and the remaining two rows have a blank value for column "blog_tag":
$tagInput = $_POST["blog_tags"];
$tagArray = explode(",",$tagInput);
$sql_2 = "INSERT INTO blog_tags (blog_tag, blog_id)
VALUES ";
$valuesArray = array();
foreach($tagArray as $row){
$tag = mysqli_real_escape_string($conxn, $row['blog_tag']);
$valuesArray[] = "('$tag','$lastID')";
}
$sql_2 .= implode(',', $valuesArray);
if (!mysqli_query($conxn,$sql_2)) {
die('Error: ' . mysqli_error($conxn));
}
This is spaghetti pieced together from various searches here and it's getting close but I can't figure out where it's grabbing just that first letter of the string.
Explode doesn't create associative arrays
$tag = mysqli_real_escape_string($conxn, $row); //instead of $row['blog_tag']
just replace your foreach with this for inserting values of array
foreach($tagArray as $row){
$a=mysqli_real_escape_string($row)
$sql_2 = "INSERT INTO blog_tags (blog_tag, blog_id) VALUES
('$a','$lastID') ";
}
What I am doing is adding values to a mysql table with each value seperated by a comma. And each new value is appended to that last value once again seperated by a comma. Now this is all dynamic. What I am having an issue is on how to remove a selected value and the comma. I am using php and mysql.
I can read the values out with explode and line[value].
table name is values
table consist of id, value, value_array
$value_selected would be a $_GET['value']
value_array is the column that contains all the values seperated by comma.
The database selects from values where the id is equal to the Get value.
Then returns all values in the value_array
I then explode the values and have each value from the value_array read through the for loop and line[value].
the code:
start php
$value_selected = $_GET['value'];
$query = mysql_query("SELECT * FROM values WHERE id='$value_selected'");
while($result = mysql_fetch_assoc($query))
{
$check_values = $result['value_array'];
}
$values = explode(",",$check_values);
$count_values = count($values);
for($counter = 0; $counter < $count_values; $counter++)
{
$line = each($values);
$query = mysql_query("SELECT * FROM values WHERE id='$line[value]'");
while($result = mysql_fetch_assoc($query))
{
echo $result['value'].'<br/>';
}
}
php end
I don't have an issue reading it out. What I'm trying to do is being able to select a value via GET and remove that value from the value_array while also removing the trailing comma. I hope I was able to expalin in more detail my issue.
Use a foreach loop, take the exploded string and reassemble it minus the string $value_selected by doing this:
$NewValue = '';
$i = 1;
foreach ($values as $Value) {
if ($i > $count_values) {
break;
} else {
if ($Value !== $value_selected) {//reassemble comma-sep string - $_GET['value']
$NewValue = $NewValue . $Value . ",";
}
}
$i++;
}
Now $NewValue no longer contains $_GET['value'], because the concatenation in the if statement only occurs when the exploded fragment $Value does not match $_GET['value']. Update the database or echo $NewValue, etc. as necessary at this point.
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.