I'm having an issue inserting an array into my database. When i tried implode, it all inserted all the arrays into one row. What i intend to achieve is to insert a single array into different rows.
In the array i have fields such as bag,shoes,cloths and i wish to insert into one table but different rows.
$subjectArray[] =$_POST['subject'];
$all_subjects_to_insert = array();
foreach ($subjectArray as $p){
if(!empty($p)) $all_subjects_to_insert = $p;
}
$all_subjects_to_insert = array_unique($all_subjects_to_insert);
$final = implode(',',$all_subjects_to_insert);
$query = "INSERT INTO #__sch_subject (subject) VALUES ('$final')";
I'll appreciate any help i get. Thanks.
if $all_subjects_to_insert is multidimensional array then what you are looking for is
foreach($all_subjects_to_insert as $value)
{
$query = "INSERT INTO #__sch_subject (subject) VALUES ('{$value}')";
mysql_query($query);
}
Reference
Thanks everyone. Its now working. The separator for the implode function was incorrect. Here is the working code
$subjectArray[] =$_POST['subject'];
$all_subjects_to_insert = array();
foreach ($subjectArray as $p){
if(!empty($p)) $all_subjects_to_insert = $p;
}
$all_subjects_to_insert = array_unique($all_subjects_to_insert);
$inserted_values = implode("'),('",$all_subjects_to_insert);
print_r($finalvalues);
$query = "INSERT INTO #__sch_subject (subject) VALUES ('$inserted_values')";
With the separator the insert command looks like this
$query ="INSERT INTO #__sch_subject (Subject) VALUES ('a'),('b'),('c')";
Thanks for the help. I really appreciate.
Related
I need to insert MySQL data from array values to a single raw. I have tried code below but I am getting error: Warning: implode(): Invalid arguments passed in
How can I solve this problem? Or is there any alternative way to insert array values to single raw in MySQL using PHP?
<?php
foreach ($_POST['qty'] as $product_id => $qty) {
$product_id = implode(" ",$product_id);
$qty = implode(" ",$qty);
}
$q = mysqli_query($conn, "INSERT INTO product_order (product_id,qty) VALUES ('$product_id','$qty')");
?>
Implode function second parameters accept Array so at first check in implode function the second parameter is array.
foreach ($_POST['qty'] as $product_id => $qty)
This line says $product_id is key which is not array so implode function should not work.
Please provide $_POST['qty'] dump
Try this:
<?php
$product = [];
$qtys = [];
if(!empty($_POST['qty'])){
foreach ($_POST['qty'] as $product_id => $qty) {
array_push($product, $product_id);
array_push($qtys, $qty);
}
$qty_final = implode(',',$qtys);
$product_id_final = implode(',',$product);
$q = mysqli_query($conn, "INSERT INTO product_order (product_id,qty) VALUES ('$product_id_final','$qty_final')");
}
It is very bad idea to save comma separated values in db.
This is not a good idea. - It is a very bad idea.
That being said. Your $product_id is not an array - it is an array key (string or integer) so there is nothing to implode.
Instead of inserting csv into this table it would be a much better idea to insert new row for each id you have.
try this :
<?php
$product_data = isset(($_POST['qty'])? ($_POST['qty']: array();
if ( !empty($product_data) ){
$sql = "INSERT INTO product_order (product_id, qty) VALUES ('".implode(", ", array_keys($product_data))."','".implode(", ", array_values($product_data))."')";
$q = mysqli_query($conn, $sql);
}
?>
If you want to post array to database then use php serialize function.It is best for array type data
$serialized_data = serialize(array('Math', 'Language', 'Science'));
echo $serialized_data . '<br>';
You could do,
<?php
$product_data = isset(($_POST['qty'])? ($_POST['qty']: array();
if ( !empty($product_data) ){
$sql = "INSERT INTO product_order (product_id, qty) VALUES ('".implode(", ", array_keys($product_data))."','".implode(", ", array_values($product_data))."')";
$q = mysqli_query($conn, $sql);
}
?>
This should work.
But keeping comma seperated list in a field is not a good thing to do. You could have a new table, so that you can keep a mapping to what products are in what order.
I use:
foreach($image_files as $index=>$file)}
to loop between pictures in a directory and list them in a webpage, every picture has three related column in the database (ID, NAME, DESCRIPTION) ... so I used
SELECT `NAME`, `DESCRIPTION` FROM `pic_info` WHERE `ID`= '$counter' ...
but i don't know how can I split the
$rows = mysql_fetch_array($result, MYSQL_ASSOC)
to 2 variable for each picture ... for example : for the first pic I need
$name[0] = pic1 and $description[0] = blahblahblah1 ...
$name[1] = pic2 , $description[1] = blahblahblah2 ...
using
foreach ($rows as $key => $value) {$$key = $value; }
just gives me a combined data like $name[0] and $description[0] that I don't know how can I split it to two variable ... and it'll be appreciated if someone show another ways to SELECT two column in a table and assign it to two variables .
It's a bit unclear what you're asking, but I think you might want something like this
$names = array();
$descriptions = array();
while($row = mysql_fetch_assoc($results))
{
$names[] = $row["NAME"];
$descriptions[] = $row["DESCRIPTION"];
}
Requires PHP >=5.5, but this might achieve what you're after
$names = array_column($rows, 'NAME');
$descriptions = array_column($rows, 'DESCRIPTION');
or simply build the arrays you want while looping through the resultset of your SQL query
hi am building a quiz system and basically i have my questions in an array called $questions and answers in an array $answers i have created an interface in html php to add data questions and answers into this arrays
$question1 = $_POST['question1'];
$question2 = $_POST['question2'];
$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];
$questions = array();
array_push($questions,$question1,$question2);
$answers = array();
array_push($answers,$ans1,$ans2);
so to insert this values in a database this is what i do
$quest_count = count($questions);
for ($i=0;$i<=$quest_count;$i++)
{
$query = "INSERT INTO quiz (question,answer) VALUES ('$questions[$i]','$answers[$i]')";
$result = mysql_query($query);
}
so my problem is this the for loop should add two rows in the database since the questions array contains two values question1 and question2 but it only adds one row. can anyone help me out on this am sure its ('$questions[$i]','$answers[$i]') part that has a problem.
thanks
You're using the <= operator in your loop.
Change it to just less than:
for ($i=0;$i<$quest_count;$i++)
{
$query = "INSERT INTO quiz (question,answer) VALUES ('$questions[$i]','$answers[$i]')";
$result = mysql_query($query);
}
Also, make sure you properly sanitise your input strings.
Please use < than using <= in the for loop, this will ensure that the loop runs twice or the exact of count of question array.
Try this:
Here no need to count array values & for loop. Instead use foreach loop.
Here is the solution:
foreach ($questions as $key1 => $que, $answers as $key2 => $ans)
{
$query = "INSERT INTO quiz (question,answer) VALUES ('$que','$ans')";
$result = mysql_query($query);
}
-
Thanks
I have a query that's retraive a list of id's. Those id's are in an array and i need to save it in table with those id's. I tried using implode to make those id's a string i could use in a where clause but i keep getting this error.
$save_food = $_POST['save_food'];
$unserializedData = array();
parse_str($save_food,$unserializedData);
foreach($unserializedData as $unserializedData1){
$query = mysql_query("insert into subscribefood (s_user_id,s_food) values ('$ft_user_id','".implode($unserializedData1, ',')."')");
}
Try this
<?php
$save_food = $_POST['save_food'];
$unserializedData = array();
parse_str($save_food,$unserializedData);
$datalist = $unserializedData['foodtype'];
foreach($datalist as $data){
$query = mysql_query("insert into subscribefood (s_user_id,s_food) values ('$ft_user_id','$data')");
}
?>
I am imploding data inside of an array, called the following:
["Levels_SanctionLevel_array"]=>
string(14) "IR01,IR02,IR03"
I need to explode this data and input each value as a row inside of mysql. Such as
pri_id value
---------------
01 IR01
02 IR02
03 IR04
Now where I am getting stuck is this:
The array listed above could have 1 value, 3 values (right now I am showing three values) or 5 values, and I dont want to input NULL values inside of my database.
Appreciate any guidance anyone can share...
$data = explode(',',$your_string);
foreach ($data AS $value) {
// INSERT INTO DB
}
A simple loop works correctly, but has the drawback of making multiple queries to the database:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
foreach ($vals AS $value) {
// insert into database
}
As DB operations are a more significant bottleneck than building a query in PHP, I would opt to generate the SQL code for a single query as follows:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
$query = 'INSERT INTO my_data VALUES ';
foreach ($vals as $value) {
$query .= "('', '".$value."'),";
}
$query = rtrim($query, ',');
// insert into database
Why don't you use an iterator over the array to construct the sql query? That way you will only insert as many elements as you have in the array.
Like the answer above. I think we were answering at the same time.
Supposing your major array is $data:
foreach ($data as $values)
{
$value = explode(",", $values);
foreach ($value as $v)
{
$sql = "INSERT INTO table(value) VALUES('$v')";
}
}