Replace value in assocative array PHP - javascript

I'm trying to echo back an array to my javascript-application from PHP and change the values of a key based on it's match.
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
if ($key == 'Service' && $value == '1')
$result[$key[$value]] = 'Dinner';
if ($key == 'Service' && $value == '2')
$result[$key[$value]] = 'Lunch';
if ($key == 'Service' && $value == '3')
$result[$key[$value]] = 'Breakfast';
}
Basically a database has numerical entries that corresponds to certain services and I'm trying to change the number to reflect the actual service but nothing I've tried so far has worked.
The only thing I'm certain of is that the above code is wrong and incredibly ugly. Is there a PHP-function that will do what I want?
On the other hand it might be easier to change the values on the javascript side but I haven't been able to do that either.
Using the ajax, angular $http method I retrieve the data with
.then(function (response) {
console.log(response);
$scope.userData = {};
$scope.userData = response.data;
I've tried changin the response.data like so;
if (response.data.services == '1') {
response.data.services = 'Dinner';
}
But that doesn't work.
Also tried
if ($scope.userData.services == '1') {
$scope.userData.services == 'Dinner';
}
Doesn't work, but I suspect that even if it did it wouldn't alter all the values of the response.data.services to correctly display what service is being referred to.

You can use arrays for mapping/lookup purposes:
// One-time definition
$services = ['1' => 'Dinner', '2' => 'Lunch', '3' => 'Breakfast'];
// Your code...
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as &$row)
{
// If the key is set and is mapped in $services
if(isset($row['Service']) && isset($services[$row['Service']]))
{
// Then replace it
$row['Service'] = $services[$row['Service']];
}
}
I think your code would also work if you replace $key[$value] with just $key, but it's kind of wasteful to use a foreach loop if you only need a single, specific key anyway.

The code should work correctly, the only thing you are missing here is that if you dont pass value as reference (&), so currently you cant make changes in your result array. You can also group a little
foreach ($result as $key => &$value) {
}

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

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.

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.

if statement in while loop

I have a PHP script that gets some data from a table in my MySQL database.
And then it sends this information back to the PHP page with JSON javascript.
It all works great but i would like to make an if statement in the while loop.
My "used" table sends back "1" and "5" instead of echoing back 1 or 5 i want it to send Yes or NO.
One way of doing this could be breaking down the $data and replace the 1 or 5 with Yes or No.
But is there any another way of doing it?
Something like: `if (used == '1') { set used == 'No } else {set used == 'Yes' }`
my code below
while ($row = $result->fetch_assoc()) {
$data['results'][] = array(
'id' => $row['id'],
'number' => $row['number'],
'type' => $row['type'],
'code' => $row['code'],
'price' => $row['price'],
'used' => $row['used'],
'utime' => $row['utime'],
'username' => $row['username']
);
}
//Everything went to plan so set success to true
$data['success'] = true;
//Set the content type for a json object and ensure charset is UTF-8. NOt utf8 otherwise it will not work in IE (Darn IE! >.<)
header("Content-Type: application/json; charset=UTF-8");
//json encode the data and cast to an object so we can reference items like this.id in the javascript instead of this['id'] etc.
echo json_encode((object)$data);
You can use the conditional operator in the array assignment:
'used' => $row['used'] == 1 ? 'Yes' : 'No',
You can do this without if statement:
$answer = array(0 => 'No', 1 => 'Yes');
...
'used' => $answer[ $row['used'] ],
...

Categories

Resources