shorter way to collect and send data without a form - javascript

I have some (15) input, select, and textarea tags on page - without a form
need to collect their values and insert them into a database
this code works fine, but I hope there is a way to short it
on client side - maybe some kind of serialize
on server side - especially on execute statement - maybe some kind of loop
$('#btn_send').on('click', function(){
let obj = {};
$('input, select, textarea').each(function(){
let a = $(this).attr('name');
obj[a] = $(this).val();
});
let str = JSON.stringify(obj);
$.post('reg.php', {fn: 'btn_send', args: [str]}, function(data){
console.log(data);
});
});
reg.php
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute([
":aname" => $obj->name,
":agender" => $obj->gender,
//... and so on - 15 items
]);
echo 'success';
}

Based on your code sample, it looks like the elements of your object have the same names as the columns in your table. In that case, you can simplify your code by converting the incoming JSON to an array rather than an object and utilising the fact that PDOStatement::execute allows the array keys to not include the : in the names:
$obj = json_decode($str, true);
// here are table columns
$cols = array_keys($obj);
$a = implode(',', $cols);
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute($obj);
Should the behaviour of execute change in the future, you can make an array with the keys preceded with : using array_combine and array_map:
array_combine(array_map(function ($k) { return ":$k"; }, $cols), $obj)
You would then pass this array to execute in place of $obj.

Something I made not sure if it even compiles, just was bored this is how I would do the 15 items or so part.
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$sqlArray = array();
foreach($obj as $key => $value) {
$sqlArray[]= array(":a".$key => $value);
}
$st->execute($sqlArray);
echo 'success';
}
Edit: I looked at Nick's answer it seems you don't even need to do all the hard stuff I did, you can just pass $obj wow they made it so easy now

Related

overriding value and creating extra value while using foreach loop

accepting serialized data array from javaScript, and i want to work with each array value of serialized data. but when data is updated its overriding name field and creating extra array with only name field.
['checked_dns=0&name=localhost.vias.jfkl.&domain=via…12520&type=A&record=*.*.*.*&ttl_sel=14400', 'checked_dns=2&name=ns1.vias.jfkl.&domain=vias.jfkl…12369&type=A&record=*.*.*.*ttl_sel=14400', 'checked_dns=3&name=ns2.vias.jfkl.&domain=vias.jfkl…15000&type=A&record=*.*.*.*&ttl_sel=14400']
This Serialized array i am receiving.
$data_arr = $_POST['arr'];
foreach($data_arr as $value){
$single_arr = [];
$single_arr = explode("&",$value);
foreach($single_arr as $val){
$single = explode("=",$val);
$final_arr[$single[0]] = $single[1];
// // Just Check
$name = $final_arr['name'];
$point = $final_arr['edit_record'];
$ttl = $final_arr['ttl_sel'];
$type = $final_arr['type'];
$address = $final_arr['record'];
// Checking done now edit record
$check = $softpanel->fun_for_update_record($point, $name, $ttl, $type, $address);
}
}

Posting a js array to PHP and using it in a database query

I want my javascript function to pass multiple variables down to PHP and then have PHP use those variables in a select statement. Currently my code works when I just pass the variables that are strings but as soon as I added this line: AND newVar IN ('+$myVarArrayPHP+') into the query, the query doesn't pull anything from the database(There definitely is a row of data that matches the query). Thanks so much!!
JS:
var varSring1= "test";
var varString2= "testing";
var varArray= [""] // the number of elements in the array is determined dynamically and are all strings for example: ["grape","mango","apple"]
$.ajax({
type: 'POST',
url: "myPHPFile.php",
data: {
myVar1: varSring1,
myVar2: varString2,
myVarArray: varArray
},
dataType: "json",
success: function (response)
if ((response[0]['var1']) != null) {
document.getElementById("tc-unique-ID-1").value = (response[0]['var1']);}
if ((response[0]['var2']) != null) {
document.getElementById("tc-unique-ID-2").value = (response[0]['var2']);}
error: function (err) {
console.error(err.responseText);
}
});
}
PHP:
if(isset($_POST[myVar1]) && ($_POST[myVar2]) && ($_POST[myVarArray])){ //check if $_POST[''] exists
$myVar1PHP= $_POST[myVar1];
$myVar2PHP= $_POST[myVar2];
$myVarArrayPHP= $_POST[myVarArray];
$ret = pg_query($connection, "SELECT * FROM table
WHERE var1= '$myVar1PHP' AND var2= '$myVar2PHP' AND newVar IN ('+$myVarArrayPHP+');")
$results=array();
while($row = pg_fetch_assoc($ret) ){
array_push( $results,$row);
}
}
You need to tell PHP how to deal with the array, e.g. by using implode (PHP documentation):
//check if $_POST['...'] exists
if(isset($_POST["myVar1"]) && isset($_POST["myVar2"]) && isset($_POST["myVarArray"]) && isset($_POST["differentPostedVar"]) && isset($_POST["lastPostedVar"])){
$myVar1PHP= $_POST["myVar1"];
$myVar2PHP= $_POST["myVar2"];
$myVarArrayPHP= $_POST["myVarArray"];
$differentPostedVar = $_POST["differentPostedVar"]; // assumption
$lastPostedVar = $_POST["lastPostedVar"];
// newVar IN ($3, $4, $5); and so on
$first_sql = "SELECT * FROM table WHERE var1= $1 AND var2= $2 AND newVar IN (put_placeholders_here);";
$results = execute_prepared_statement($connection, $first_sql, "first_sql", array($myVar1PHP, $myVar2PHP), $myVarArrayPHP);
if(0 == count($results)) {
$second_sql = "SELECT * FROM table WHERE differentVar= $1 AND var2= $2 AND newVar IN (put_placeholders_here);";
$results = execute_prepared_statement($connection, $second_sql, "second_sql", array($differentPostedVar, $myVar2PHP), $myVarArrayPHP);
if(0 == count($results)) {
$third_sql = "SELECT * FROM table WHERE 3rdQ= $lastPostedVar;";
$results = execute_prepared_statement($connection, $third_sql, "third_sql", array($differentPostedVar, $myVar2PHP), $myVarArrayPHP);
}
}
echo json_encode($results);
}
function execute_prepared_statement($connection, $sql, $query_name, $normal_params, $in_array = null) {
$elementsCount = count($in_array);
$no_of_other_params = count($normal_params); // you need to start with $3 because of $myVar1PHP and $myVar2PHP
// generate an array that holds a placeholder ($3, $4 etc.) for every value in $myVarArrayPHP
$binding_placeholders = array();
for($i = 0; $i < $elementsCount; $i++) {
$binding_placeholders[] = "$" . ($i + $no_of_other_params + 1);
}
// array to string conversion (will produce "$3,$4,$5" etc.)
$placeholders = implode(",", $binding_placeholders);
// replace placeholder string with actual placeholder string
$sql = str_replace('put_placeholders_here', $placeholders, $sql);
$ret = pg_prepare($connection, $query_name, $sql);
// using array_merge to create one array having all parameters
$parameters = array_merge($normal_params, $in_array);
$result = pg_execute($connection, $query_name, $parameters);
$results=array();
while($row = pg_fetch_assoc($ret) ){
array_push( $results, $row );
}
return $results;
}
implode(',', $array); converts ["grape", "mango", "apple"] to a string: grape,mango,apple. Now SQL is able to deal with it.
Documentation for the pg_prepare() prepared statement: PHP Documentation
EDIT
I was missing the " around the indices of the arrays
implode() was the right idea but I used it for the wrong thing because it will generate "grape, mango, apple" so your database will look exactly for this string. Instead, we need to look for "grape", "mango", "apple".
Using the splat operator of PHP to disassemble $myVarArrayPHP dynamically.
Inspiration from https://supunkavinda.blog/php-mysqli-prepared-where-in.
2ND EDIT
Answer to another question by thread opener to execute several queries based on count($results) of previous statements.

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'id_paket' at row 1

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'id_paket' at
row 1 (SQL: insert into tbl_pesanan (id_paket, kode_bmn,
kode_unit, jenis_barang, kuantitas, satuan_ukuran,
status_pesanan) values (18,18, 1010101002,1010101002, 1001,1001,
ASus,ASus, 6,6, UNit,UNit, 1))
what happened, can you help me?
public function store_pesanan(request $request,$id){
if(!Session::get('login')){
return redirect('/login')->with('alert','Kamu harus login dulu');
}
else{
DB::table('tbl_paket')
->where('id_paket',$id)
->update(['status_paket' => $request->status_paket]);
$data = new ModelPesanan();
$data->id_paket = implode(',', $request->input('id_paket'));
$data->kode_bmn = implode(',', $request->input('kode_bmn'));
$data->kode_unit = implode(',', $request->input('kode_unit'));
$data->jenis_barang = implode(',', $request->input('jenis_barang'));
$data->kuantitas = implode(',', $request->input('kuantitas'));
$data->satuan_ukuran = implode(',', $request->input('satuan_ukuran'));
$data->status_pesanan = $request->get('status_pesanan');
$data->save();
Alert::success('Sukses!', 'Berhasil Menambahkan Pesanan!');
return redirect ('/daftar_paket');
}
}
The issue seems to be that you are trying to insert a value in the field id_paket that is too long. Check the type and size of id_paket and compare to what your query is sending: 18,18
You should not try to save arrays into a single field unless they are intended to be kept as a json.
I think you are trying to create two ModelPesanan? if so, assuming id_paket is a foreign key and the key of the id_paket array is the same for all the other arrays in the request then you can try:
DB::table('tbl_paket')
->where('id_paket',$id)
->update(['status_paket' => $request->status_paket]);
foreach($request->input('id_paket') as $index => $idPaket){
$data = new ModelPesanan();
$data->id_paket = $request->input('id_paket')[$index];
$data->kode_bmn = $request->input('kode_bmn')[$index];
$data->kode_unit = $request->input('kode_unit')[$index];
$data->jenis_barang = $request->input('jenis_barang')[$index];
$data->kuantitas = $request->input('kuantitas')[$index];
$data->satuan_ukuran = $request->input('satuan_ukuran')[$index];
$data->status_pesanan = $request->get('status_pesanan');
$data->save();
}
Alert::success('Sukses!', 'Berhasil Menambahkan Pesanan!');
return redirect ('/daftar_paket');

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

nested javascript array to php array

I have a javascript array :
disharray = ([aa,11,],[bb,22])
I send this to php as a json object using - var jsoncvrt = JSON.stringify(disharray);
How do I extract the value of the nested arrays so that I can access values like:
$a = aa and $b = 11?
I use the below code but get the output as
aa11
bb22
Please note, my server uses php 5.2
$data = json_decode(stripcslashes($_POST['strings']));
foreach ($data as $d => $v) {
foreach ($v as $v1 => $value) {
echo $value;
}
}
Your code is fine. Just add this at the top of the code
$values = array();
Now change the inner foreach loop to
if( sizeof($v) == 2 ){
$values[$v[0]] = intval($v[1]);
}
Now to access, say the value corresponding to 'aa' just use $values['aa']
You can insert it into a table using the following code
$con = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DBNAME);
$query = "INSERT INTO tablename (key, value) VALUES(?, ?);";
$stmt = $con->prepare($query);
if( $stmt ){
foreach ($values as $key => $value){
$stmt->bind_param("sd", $key, $value);
$stmt->execute();
}
$stmt->close();
}
$con->close();
In the $query variable, the '?' stands for wild card character that can take any value and it is set by calling bind_param() function. In the bind_param function, the 's' stands for string and the 'd' stands for integer data type. This is the right way to execute database queries as they void the possibility of SQL Injections.

Categories

Resources