if statement in while loop - javascript

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'] ],
...

Related

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 - Javascript result inside MySQL

I don't understand why every column has good results but the screen column has code inside and not the actual SCREEN SIZE (result of the code).
<?php
#$data = $_SERVER['HTTP_USER_AGENT']."|";
#$data.= $_SERVER['HTTP_CF_CONNECTING_IP']."|";
$width = " <script>document.write(screen.width); </script>";
$height = " <script>document.write(screen.height); </script>";
$data.=$width;
$data.=$height;
$finz = explode("|",$data);
$ag = $finz[0];
$ip = $finz[1];
$sc = $finz[2];
$query1 = $db->prepare("INSERT INTO `checks` (user,type,ip,screen,agent) values (:user,:type,:ip,:screen,:agent)");
$query1->execute(array(
'user' => $USER['username'],
'type' => 'Red Flower',
'ip' => $ip,
'screen' => $sc,
'agent' => $ag
));
$row2 = $query->fetch();
?>
Can somebody tell me how to make the code insert the values of the JavaScript output without using POST AJAX/JQuery etc?
The embedded JavaScript won't be evaluated until your template reaches the client. It's not something the PHP interpreter understands. It's just a string. You have to execute this code in JavaScript and send it back to the server, there's no other way.
You will need to send a request back to the server containing the results of the evaluated JavaScript before performing the query against your database.
I realize this is something you were trying to avoid.

Error in cookie law info plugin for Wordpress

I've got a problem with one of my plugins.
The log files said:
PHP Warning: stripslashes() expects parameter 1 to be string, array given in /mnt/web008/c1/24/57250724/htdocs/WordPress_01/wp-content/plugins/cookie-law-info/php/shortcodes.php on line 125
It looks like that there is an aray given but a string expected? I dont know how i can fix this.
/** Returns HTML for a standard (green, medium sized) 'Accept' button */
function cookielawinfo_shortcode_accept_button( $atts ) {
extract( shortcode_atts( array(
'colour' => 'green'
), $atts ) );
// Fixing button translate text bug
// 18/05/2015 by RA
$defaults = array(
'button_1_text' => ''
);
$settings = wp_parse_args( cookielawinfo_get_admin_settings(), $defaults );
/*This is line 125:*/ return '' . stripslashes( $settings ) . '';
}
Well, the error itself is pretty self explanatory.
The function stripslashes expects its parameter to be a string. A quick look at the Wordpress documentation suggests that the return value of wp_parse_args is an array, meaning the $settings variable is an array not a string and therefore passing it as an argument in stripslashes causes your error.
You can use stripslashes on an array, however, it requires a little bit more work. Here's the example given in the PHP documentation.
<?php
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// Output
print_r($array);
?>
https://developer.wordpress.org/reference/functions/wp_parse_args/
http://php.net/manual/en/function.stripslashes.php
EDIT: It's probably worth noting that stripslashes_deep will return an array. If this is not the desired output then wrap the call the stripslashes_deep function via the implode function to convert it to a string.
implode(stripslashes_deep($settings))

Replace value in assocative array PHP

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

JSON passes string instead of array or object from PHP to Javascript

I am having som trouble with passing a multidimensional and associative array from php to Javascript. I converte it with JSON, using:
_SESSION = '<?php print json_encode($_SESSION) ?>';
I have also tried
_SESSION = '<?php print json_encode($_SESSION, JSON_PRETTY_PRINT) ?>';
_SESSION = $.parseJSON('<?php print json_encode($_SESSION) ?>');
both of them give me errors like: Uncaught SyntaxError: Unexpected token ILLEGAL.
However, the first one doesn't give me any errors and I can access it in Javascript. It then outputs:
{"items":{"221163":{"CodeComplete":null,"Project":"Coding","Team":"Mail","TimeSpent":25","Children":[]}}, {"221165":{CodeComplete":null,"Project":"Coding","Team":"Batman","TimeSpent":"40","Children":[]}}
I belive this is like a string, since _SESSION[0] outputs "{". However, I want it to be an array or an object. The Array looks like this in php:
_SESSION( "items" => array(
221163 =>
array( CodeComplete => null
Project => "Coding"
Team => "Mail"
Timespent => "25"
Children => array(
)
)
221165 =>
array( CodeComplete => null
Project => "Coding"
Team => "Stones"
Timespent => "40"
Children => array(
)
)
)
)
I want to be able to access this array in the same way as I can in php (not litterary ofcorse) but _SESSION["items"] or _SESSION.items is undefined as _SESSION is a string...
Any ideas of what I'm doing wrong?
Just as #CD001 suggested in his comment, I removed the '' from the transfer so that it became
_SESSION = <?php print json_encode($_SESSION) ?>;
instead and now everything works fine, thank you!

Categories

Resources