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)
}
Related
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]);
}
I have a json array which needs to be parsed in such a way that I can update multiple rows in one mysql query.
This is my json array:
[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"}
,{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"}
,{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]
I am trying a update query something like this:-
$query="UPDATE urd_voucher_table SET voucher_status ='$status', doc_no = '$docNo' WHERE voucher_id ='$vc_id'";
I want to know how can I parse the above json in order to get individual values for voucher_status, doc_no and voucher_id.
Any help is appreciated.Thank you.
Use json_decode()
Decode the JSON and loop over the decoded array.
<?php
$json = '[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]';
$arr = json_decode($json, TRUE); // Observe the second parameter. If it is TRUE, associative array will be returned irrespective of what json is.
if (! empty($arr)) {
foreach ($arr as $elem) {
extract($elem);
$query="UPDATE urd_voucher_table SET voucher_status ='$voucher_status', doc_no = '$doc_no' WHERE voucher_id ='$voucher_id'";
// Add your code here.
}
}
Reference of extract()
use json_decode() it will return an associative array with key, value pair like :
$strJson = '[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]';
$arr = json_decode($strJson);
will return:
Array ( [0] => stdClass Object ( [doc_no] => ADV103 [voucher_status] => closed [voucher_id] => URDV1000 ) [1] => stdClass Object ( [doc_no] => ADV103 [voucher_status] => closed [voucher_id] => URDV1001 ) [2] => stdClass Object ( [doc_no] => ADV103 [voucher_status] => closed [voucher_id] => URDV1003 ) )
now using loop you can fetch data & insert/update database.
You need to decode the json string into an array, loop through the results and run the update query. Please see my example below...
$rows = json_decode('[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]');
foreach ($rows as $row) {
$query="UPDATE urd_voucher_table SET voucher_status ='{$row['voucher_status']}', doc_no = '{$row['doc_no']}' WHERE voucher_id ='{$row['voucher_id']}'";
// ... Run query etc..
}
First use json_encode() and then iterate result array in foreach. Like following:
$jsonString = '[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]';
$json_decoded = json_decode($jsonString);
foreach($json_decoded as $index=>$val){
$status = $val->voucher_status;
$docNo = $val->doc_no;
$vc_id = $val->voucher_id;
$query="UPDATE urd_voucher_table SET voucher_status ='$status', doc_no = '$docNo' WHERE voucher_id ='$vc_id'";
//execute query here
}
More info on http://www.geeksengine.com/database/data-manipulation/bulk-insert.php
Follow these steps
decode json
apply foreach loop per record
Built and concat data for this part for each record in JSON
for e.g. (a,e,r),(br,t,y),(t,y,c);
Hard code this part in query "Insert into table (c1,c2,c3) VALUES "
And attche data that was created in step 3.
Final query will be
Insert into table (c1,c2,c3) VALUES . STEP 3
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')");
}
}
Hello i have a dynamic form that can change field names upon user selection. i would like for the form result to be inserted into one mysql row.. i create an array as follows:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
}else{
$results = $variable;
$columnName = $key;
$array[] = array($columnName => $results);
}
}
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
?>
my array result are
(
[0] => Array
(
[Server_id] =>
)
[1] => Array
(
[Server_IP_Address] => 12345
)
[2] => Array
(
[Server_IP] => 12345
)
[3] => Array
(
[Server_Name] => dad
)
)
How can i have the array be inserted in one table row and reference the $results and the field value and $columnName as the field value.
You could use a few php built in functions:
function put_quotes(&$item){
$item = "'$item'";
}
$columns = implode(",",array_walk(array_keys($_POST),'put_quotes'));
$values = implode(",",array_walk(array_values($_POST),'put_quotes'));
mysql_query("INSERT INTO $table (columns) VALUES ($values) ")or die(mysql_error());
Where :
array_walk executes a function over all array, here put quotes over the item.
array_keys gets the keys from an array
array_values gets the values from an array
implode joins an array to a string with a separator
Use PDO because mysql_* functions are depreceated.
Connect to MySQL in PDO :
$db="database";
$host="127.0.0.1";
$usr="username";
$pass="password";
$dbh=new PDO("mysql:dbname=$db;host=$host", $usr, $pass);
First convert the array to JSON and save it on the table :
$json=json_encode($array);
$sql=$dbh->prepare("INSERT INTO ? (?) VALUES (?)");
$sql->execute(array($table,$columnName,$json));
If you want to retrieve the array back, decode the JSON data got from table:
$sql=$dbh->prepare("SELECT ? FROM ?");
$sql->execute(array($columnName,$table));
while($r=$sql->fetch()){
$array=json_decode($r[$columnName],true);
print_r($array);
}
what is the optimal way for me to insert and array of 1000 lines and 10 columns each into a mysql table below is how i display it so it would be a similar construct but i need some directions
foreach ($stack as $val) {
print "<tr>\n";
foreach ($val as $no) {
print " <td>$no</td>\n";}
print "</tr>\n";
}
You can insert multiple rows with a single insert as follows :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
look at implode() to create the values string from your array
Better way to insert thousands of data into DB is to use implode function implode
i'm guessing u got something like this
$stack = array("man1" => array("name"=>"ik", "class"=>"highskl", "age"=> "12"),"man1" => array("name"=>"ijk", "class"=>"higkl", "age"=> "13"));
and you want to insert them into a table, try and use the table fields as index for the inner arrays then adjust the code to look like this
foreach ($stack as $entry => $value) {
$query = "INSERT INTO table set ";
foreach ($value as $key => $val) {
$query .= $key ."= ".$val.",";}
//use a string function to remove the last comma
$result = mysql_query($query) or die("Error in Query ".$entry." ",mysql_error());
//this helps to track error..
}