Inserting array into table - php

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.

Related

Laravel database insert with combining array and string

I should insert an array such as $attendanceList = [18354012,18354013,18354014,18354015] and $present = "FALSE" and same for all item of $attendanceList. As you see $attendanceList is array but $present is String.
When I insert like DB::table("attendance")->insert(["id"=>$attendanceList,"present"=>"FALSE"]) returns error.
What should I do? Pairing all item of $attendanceList and $present or there are another ways?
Note: I don't want to use loop if it is possible.
You can prepare array from your data and do bulk insert in one query:
<?php
$attendanceList = [18354012,18354013,18354014,18354015];
$present = "FALSE";
$insertData = array_map(
fn($el)=>['id'=>$el, 'present'=>$present],
$attendanceList
);
$db::table("attendance")->insert($insertData);
Test Laravel DB insert online
I'm not sure why you don't want to use a loop. If you want to insert four separate rows, you're going to need one:
foreach ($attendanceList as $id) {
DB::table("attendance")->insert(["id" => $id,"present" => $present]);
}

Insert array to to single MySQL raw with foreach

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.

Posting multiples dynamically created inputs and inserting them into a MySQL database

I have a table that was dynamically created using jquery. Now I am sending the inputs, that are array, of course, to a database. The fields are customCLASSE[], customQTY[], customPRICE[]... and this is my script that inserts the data within MySQL:
if ($_POST['customCLASSE']) {
foreach ( $_POST['customCLASSE'] as $key=>$value ) {
$query = $mysqli->query("INSERT INTO booking_multiday_detail (classe) VALUES ('$value')");
}
}
It is working very good but my question is: How do I insert the other inputs (customQTY[], customPRICE[]...) within the same foreach in the same time that customCLASSE is being inserted?
$key is the index of array on looping cycle.
So if your other arrays sorted as well as customCLASSE you can access other arrays' value by $key like this,
if ($_POST['customCLASSE']) {
foreach ( $_POST['customCLASSE'] as $key=>$value ) {
$customQty = $_POST['customQTY'][$key];
$customPRICE= $_POST['customQTY'][$key];
//change the query
//....
$query = $mysqli->query("INSERT INTO booking_multiday_detail (classe) VALUES ('$value')");
}
}

PHP loop make variable available in the next loop

I have a loop like this (just a sample, many vars are missing):
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}
Now as you see $insertedIDs[] is getting in the array all the new inserted IDs.
The problem is that on the next $inserts loop I'll need that $insertedIDs[] to be available for other variables of the loop, that will need to get the last inserted ID.
The problem is that on the next loop this variable is not recognized and it returns errors.
How can I make $insertedIDs[] available on each next loop after the first loop?
I tried declaring $insertedIDs[] as global just after the foreach but no luck.
Try this may be it'll help you:
$insertedIDs=Array();
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[] = array($tables[$tbl]['owner'] => $insert_update);
}
Now you are able to access $insertedIDs
$insertedIDs = array();
foreach($inserts as $insert) {
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIDs[ $tables[$tbl]['owner'] ] = $insert_update;
}
print_r($insertedIDs);
Pretty easy actually... Try not to over-think it.
//create an empty array
var $insertedIds = array();
//now loop and add to the array
foreach( $inserts as $insert )
{
$insert_update = 'INSERT INTO etc.. SET etc..'; // returns the last inserted ID
$insertedIds[][$tables[$tbl]['owner']] = $insert_update;
//or if you want the owners to be keys in the first level of the array...
//$insertedIds[$tables[$tbl]['owner']] = $insert_update;
}
//output the contents of the array
echo '<pre>' . print_r($insertedIds, true) . '</pre>';

save data to table by serialize and php

i am use serialize to get data from page to another page by ajax like this :-
var txtCoursesNamewith = $('#with').serialize();
and get it on php page like this :-
$txtCoursesNamewith = ($_POST['txtCoursesNamewith']);
$unserializedData = array();
parse_str($txtCoursesNamewith,$unserializedData);
when print this array its like this :-
[txtCoursesNamewith] => Array
(
[0] => qq
[1] => ff
)
i need to insert this array to my table by foreach, i am try like this :-
foreach ($unserializedData as $value => $key )
but it store in database like this " Array ", how can i store (qq,ff) on table.
You can use implode() function.
$txtCoursesName = implode(",", $txtCoursesNamewith);
Then insert $txtCoursesName as a string.
use this
foreach ($unserializedData as $key => $val ) {
//your query insert into table_name(column_name) values ($val)
}
'Array' in dbrow means you are inserting unserialized array.
instead of:
INSERT INTO table (column) VALUES ({$value})
do:
INSERT INTO table (column) VALUES ({serialize($value)})
Iterate the query in loop or construct an array and execute a single insert query
foreach ($_POST['txtCoursesNamewith'] as $key => $val ) {
//your query insert into table_name(column_name) values ($val)
}

Categories