overriding value and creating extra value while using foreach loop - javascript

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);
}
}

Related

shorter way to collect and send data without a form

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

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. ;)

PHP to decode JSON array and insert into MYSQL database

I am trying to create a PHP script that decodes a JSON array and insert it into a database. So far i've managed to get the script to insert the first row in the array and nothing else.
What would I need to add to this to get the script to insert all the rows in the array?
Here's the array, ignore "listings", I don't need that data yet (It's quite big):
json
Here's the script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$con = mysql_connect($servername, $username, $password);
//select db
$selected = mysql_select_db("ed",$con);
$json_obj = file_get_contents("stations.json");
//convert to stdclass object
$arr = json_decode($json_obj,true);
//store the element values into variables
$id = $arr[0]["id"];
$name = $arr[0]["name"];
$system_id = $arr[0]["system_id"];
$max_landing_pad_size = $arr[0]["max_landing_pad_size"];
$distance_to_star = $arr[0]["distance_to_star"];
$faction = $arr[0]["faction"];
$government = $arr[0]["government"];
$allegiance = $arr[0]["allegiance"];
$state = $arr[0]["state"];
$type = $arr[0]["type"];
$has_blackmarket = $arr[0]["has_blackmarket"];
$has_commodities = $arr[0]["has_commodities"];
$has_refuel = $arr[0]["has_refuel"];
$has_repair = $arr[0]["has_repair"];
$has_rearm = $arr[0]["has_rearm"];
$has_outfitting = $arr[0]["has_outfitting"];
$has_shipyard = $arr[0]["has_shipyard"];
//insert values into mysql database
$sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard)
VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')";
if(!mysql_query($sql,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
?>
try this.
$arr = json_decode($json_obj,true);
$sql = 'INSERT INTO stations (`';
$sql.= implode('`,`', array_keys( $arr[0] ) );
$sql.= '`) values (\'';
$sql.= implode('\',\'', $arr[0] );
$sql.= '\')';
Use foreach
$arr = json_decode($json_obj,true);//decode object
foreach($arr as $ar){
$id = $ar["id"];
$name = $ar["name"];
$system_id = $ar["system_id"];
$max_landing_pad_size = $ar["max_landing_pad_size"];
$distance_to_star = $ar["distance_to_star"];
$faction = $ar["faction"];
$government = $ar["government"];
$allegiance = $ar["allegiance"];
$state = $ar["state"];
$type = $ar["type"];
$has_blackmarket = $ar["has_blackmarket"];
$has_commodities = $ar["has_commodities"];
$has_refuel = $ar["has_refuel"];
$has_repair = $ar["has_repair"];
$has_rearm = $ar["has_rearm"];
$has_outfitting = $ar["has_outfitting"];
$has_shipyard = $ar["has_shipyard"];
//insert values into mysql database
$sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard)
VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')";
if(!mysql_query($sql,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
}
For big amounts of data like in this case, you would want to execute the query just once, or you'll burden your database unnecessarily. For this, you can build your query with all the data being inserted and then execute it, like so:
<?php
$arr = json_decode($json_obj,true);//decode object
$query = "INSERT into stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard) values ";
foreach($arr as $ar) {
$query .= "($ar['id'],$ar['name'],$ar['system_id'],
$ar['max_landing_pad_size'],$ar['distance_to_star'],$ar['faction'],
$ar['government'],$ar['allegiance'],$ar['state'],
$ar['type'],$ar['has_blackmarket'],$ar['has_commodities'],
$ar['has_refuel'],$ar['has_repair'],$ar['has_rearm'],
$ar['has_outfitting'],$ar['has_shipyard']),";
}
$query = rtrim(",",$query);
if(!mysql_query($query,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
In case you want to know, your original code doesn't work because you're just grabbing the first row from the json ($arr[0]). You need to loop through the data to get all the rows.

parse string element in JSON array to integer

$con = new DBConnector();
$sth = $con->Query("SELECT medicinename as label, factor as data FROM medicine_master_tbl limit 4");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
echo json_encode($rows);
there is no problem with my query,but the returned value is ..
[{"label":"rrp","data":"5"},{"label":"t","data":"34"},{"label":"tt","data":"4"},{"label":"nutrachin","data":"45"}]
i need the json array as like below..
[{"label":"rrp","data":5},{"label":"t","data":34},{"label":"tt","data":4},{"label":"nutrachin","data":45}]
which the data is considered as string in this array , i need to be parse it as integer .. thanks in advance.
An easy one.
while ($r = mysql_fetch_assoc($sth)) {
$r["data"] = intval($r["data"]);
$rows[] = $r;
}
Ideally your database connector would allow you to specify what type of data you are returning in the row, if factor is a numeric type. For instance, PDO and mysqlnd can return native types (see How to get numeric types from MySQL using PDO?).
However, you can do the following:
while ($r = mysql_fetch_assoc($sth)) {
$r['data'] = intval($r['data']);
$rows[] = $r;
}
This way, your JSON encoding will have an integer.

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