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.
Related
I am trying to insert data from array to mysql table. If I have for example in array three items, the result of echo is Item1Item2Item3 but in the mysql table is inserted only Item3. Why it dont repeat inserting into table?
<?php
session_start();
foreach($_SESSION['cart'] as $item){
$sql="INSERT INTO eshopadmin (Item)
VALUES
('$item[item]')";
echo $item[item];
}
?>
Try something like this:
<?php
session_start();
$data; //array that will store all the data
foreach($_SESSION['cart'] as $item){
// push data to the array
array_push($data,$item[item]);
$data= implode(",", $data);
}
$sql="INSERT INTO eshopadmin (Item)
VALUES
('$data')";
?>
Very common practise to use implode and explode for retrieving arrays to and from a database table field.
$array = array('a','b','c');
$sql = 'INSERT INTO eshopadmin (Item) VALUES ("'.implode(',', $array).'")';
the array is stored as a,b,c
and when retrieving it :
$row = mysql_fetch_assoc($result);
$array = explode(',', $row['Item']);
You could use prepared statements as well. I'm used to MySQLi.
<?php
// loop only if cart is array and has items
if( is_array( $_SESSION['cart'] ) && count( $_SESSION['cart'] ) ){
// autocommit off
$mysqli_instance->autocommit( false );
// prepare insert sql
$insert_statement = $mysqli_instance->prepare( '
INSERT INTO eshopadmin
( Item )
VALUES
( ? )
' );
// bind variables to the statement
$insert_statement->bind_param( 'i', $item_array_item_value );
// loop throught array
foreach( $_SESSION['cart'] as $item ){
$item_array_item_value = $item['item'];
$insert_statement->execute();
}
// manually commit
$mysqli_instance->commit();
// restore autocommit
$mysqli_instance->autocommit( true );
}
PS: I just realized it's a really old post. Don't know why was it listed in the latest feed.
I am trying to create functions to run mysql queries
How would I do things like insert queries. I was thinking
function insert_query ($table,$cols,$values)
{
$sql="insert into $table ($cols) values ($values) "; ...etc
}
With the rest of the query code in the function. But how would I add multiple columns and values?
Should I make $cols and $values An array inside the function?
This is a function of my Database Class.
public function insert($table,$values){
$fieldNames = "";
$fieldValues = "";
foreach($values as $key => $value){
$fieldNames .= "$key,";
$fieldValues .= "$value,";
}
$fieldNames = substr($fieldNames,0,-1);
$fieldValues = substr($fieldValues,0,-1);
$sql = "INSERT INTO $table($fieldNames) VALUES ($fieldValues)";
$this->newConnection();
$result = $this->mysqli->query($sql);
$this->closeConnection();
return $result;
}
Here is what I'm using. Pass field name and Value as Array key and value. $lsQry is an array of field name & value pair
function insert_record($table,$lsQry)
{
$fields_str = implode(',',array_keys($lsQry));
$data_str = implode("','",$lsQry);
$data_str = "'" . implode("','", $lsQry) . "'";
$lsQry = "INSERT INTO $table($fields_str) VALUES($data_str)";
$rs = mysql_query($lsQry);
if(isset($rs))
return true;
else
return false;
}
Please Note
For this function, do consider that function is getting an array of fields name and value pair. It is assumed that htmlentities() and addslashes() or any escaping functions are already applied while creating array from post/get values.
Easy, just us arrays
function insert_query ($table,$cols,$values){
$sql="insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
insert_query('exampleTable', array('column_1', 'column_2', 'column_3'), array('a', 123, 'c') );
The implode for the values requires a small sidenote:
Strings always required being wrapped in quotes. Therefor I made the implode with single qoutes. The downside to this is that integets (like 123 in the example) also get wrapped.
This is not a big problem, but if you want you could replace the implode with a foreach that uses is_numeric to check wether it should be wrapped in quotes.
IMPORTANT SECURITY NOTE:
In this example I havent used proper seurity, like escape_string(), this has to be added! I've not added thos to keep the examples smaller
Another approach could be key/value-usage of an array:
function insert_query ($table,$data){
$cols = array_keys($data);
$values = array_values($data);
$sql = "insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
$info = array('column_1'=>'a', 'column_2'=>123, 'column_3'=>'c');
$info['example'] = 'Easy method to add more key/values';
insert_query('tableName', $info);
In this case you can use functions similar to codeigniter functions.
Use arrays to store table name and columns or values
For example:
$data = array('hid' => $hcsdate,'start_date' => $sdate, 'end_date' => $edate, 'title' =>$title);
Here $data holds the column name and corresponding values.
And pass this $data to another functions for insert, update etc..
I have an array which contains $player_ids. The array was obtained in a form which the user used to select his team. I then query the database with the $player_ids array.
As such:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
}
var_dump($selected);
The above code is working and when I open it in my browser I get this output
Now I want to extract the values from array $selected (which contains the names of players selected) and upload it to a database. I try to do this as follows:
foreach ($selected as $player){
$sql = mysql_query('INSERT INTO `team`(`player_name`) VALUES ("$player")')
or die(mysql_error());
print ($player);
echo'<br>';
` }
Im suspecting the above code is where the problem comes in. when the above code is executed the database contains only the array name itself and not the actual values of the array. As the following picture shows:
If anyone could point me in the right direction, as to why the array name and not its values gets saved in the database it would be greatly appreciated.
Thanks in advance.
You must put double quotes around your string instead of single quotes. In single quoted strings variables like $player are not replaced by their value interpreted there as text.
use this:
'INSERT INTO `team`(`player_name`) VALUES ("' . $player . '")'
instead of this:
'INSERT INTO `team`(`player_name`) VALUES ("$player")'
Just replace following code with your ones code and it will work efficiently.
foreach ($selected as $player){
$sql = mysql_query("INSERT INTO `team`(`player_name`) VALUES ('$player')")
or die(mysql_error());
echo "$player<br />";
}
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'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.