It appears that json_encode is being VERY picky about what other stuff can be inside my PHP file. Which is fine, because I just do what I normally would do in file A (with json_encode) in it's own file.
I just thought I would ask because I am storing a variable in the $_SESSION instead of updating my database with the variable because json_encode doesn't seem to want to work when I have all of the code in its file.
For instance, this code doesn't work:
<?php
session_start();
include 'dbcon.php';
$sessionID = uniqid();
echo json_encode($sessionID);
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
When going to the file in my browser, I do in fact get the json_encode results, however when my Javascript calls it it doesn't seem to correctly import it.
So, for now I simply have two PHP files:
<?php
session_start();
$sessionID = uniqid();
$_SESSION["sessionID"] = $sessionID;
echo json_encode($sessionID);
?>
Which echo's the same thing as in the first file, but this time my JavaScript correctly imports it.
and
<?php
session_start();
include 'dbcon.php';
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$sessionID = $_SESSION["sessionID"];
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
I guess my question is, why does this happen? It seems kind of silly that I have to store the uniqid in a SESSION so that my other PHP file can add it to the database. Whereas if I simply had it in one file, then I could just update the database when I generate a new uniqid and avoid having to use $_SESSION in the first place.
You have this:
$sessionID = uniqid();
echo json_encode($sessionID); // "53d4c17abfe87"
Since uniqid() produces a plain string, your output is not valid JSON as per the format specification. You'll need something like this instead:
$sessionID = uniqid();
echo json_encode(array($sessionID)); // ["53d4c17abfe87"]
Why does json_encode() generate invalid JSON in the first place? Because some times it's useful to generate partial JSON. For instance, it's a handy trick to inject values into generated JavaScript code:
var foo = <?=json_encode($sessionID)?>;
It's also documented:
PHP implements a superset of JSON - it will also encode and decode
scalar types and NULL. The JSON standard only supports these values
when they are nested inside an array or an object.
So to answer the question title:
Is json_encode extremely picky?
On the contrary, it's fairly relaxed!
You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.
So, what you would want would be something like this:
echo json_encode(array('sessionID' => $sessionID));
And then when you parse the JSON with JavaScript you can access it like this:
obj = JSON.parse(jsonObj);
alert(obj.sessionID);
Obviously, jsonObj is the JSON passed from the server.
Hope this helps!
Related
I am used to update a javaScript variable manually each day this way
<script>
var data = [
['Austria','IBM','8284927','UF93NV', '10'],
['Spain','Dell','1098193','MN87QA', '4'],
...
];
//rest of my code
<script>
I want to pass the values to this variable from an SQL query result using PHP so that I don't need to type several lines each day.
I have created this PHP file where I am connecting to my database and storing the result of the query in an array.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="*******";
$db="*******";
$user="*******";
$pass="*******";
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=*******;Port=1456", $user, $pass);
$sth = $dbDB->prepare("SELECT top 2 [Country],[Customer Name],[Purchase Number],[Part Number],[Qty] FROM *******");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
?>
It's working fine as you see below the result
Now I want to pass the values in the variable $result to my variable data inside the javaScript tag using jason_encode.
I added the following code in the same PHP file
<script type="text/javascript">
var data = <?php echo json_encode($result); ?>;
alert(data.toString());
</script>
But when I added the alert to see the value of my variable data I receive this
and my variable should be this way
var data = [
['Austria','Tech Data Service GmbH','3508224010','01HV707', '4'],
['Austria','Tech Data Service GmbH','3508314557','40M7578', '1']
];
Any advises please what am I missing ? Thank you.
The data is already there in your variable. To check how it your objects look like, you could use alert(JSON.stringify(data)).
The contents of your data variable won't be arrays in JavaScript as associative arrays in PHP are objects in JSON.
To get the result you want, the simplest solution would be to use $result = $sth->fetchAll(PDO::FETCH_NUM);.
Hello I am trying to output my mysqli database to a js file after encoding it, I have no trouble encoding it with json_encode but how can I get it into a js file (updating every time the mysqli data is updated)
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM tablename")) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
Any help or insight would be great! thanks
To return a json file you will have to set json headers at the top of your PHP code:
header('Content-Type: application/json');
If you just want to write the json code into an external file you would have to use PHPs fwrite().
However you can't automatically update the file, when the database is updated. You need to call your PHP file in order to update the json file.
Maybe you can solve this by using a MySQL trigger in your database, more information here.
I'm trying to get PHP code like this to work:
<?php
$hostname = '******';
$database = 'firstdb';
$username = '*****';
$password = '*****';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$sortvalue = "datbase_percent";
$sortorder = "ASC";
$sql = "select * from advanced_data where category like age_group order by {$sortvalue} {$sortorder};";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
?>
What I want to be able to do is define the $sortvalue and $sortorder via an AJAX call. I'm getting it now like this:
$.getJSON('all_get_2.php', function(data) {
Two questions...my PHP code doesn't work because I can't figure out the proper syntax for building the $sql variable the makes up the mySQL query. I've tried a bunch of things, but keep getting 500 errors. If I just type in the values, then the code works, so I know it's just a problem with my syntax.
Second question...what's the best way to pass a variable into $sortvalue and $sortorder from my front end? I know it's something using $.ajax, but not sure of the best way to do it. The idea is that the user would click a button, which corresponds with sorting a chart ascending or descending and reloads the chart without reloading the page. Any direction here would be appreciated.
I have a javascript method in separate js file that I want to call from a HTML page with a php argument.
<?php
include "connection.php";
$selectedpatient = $_POST['patient_dropdown'];
$myquery = "SELECT * FROM `patient_info` patient_info.Name = '$selectedpatient' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
<script> data_arrival($_tempdata); </script>
And I defined the source for the javascript file in the HTML header. It displays two errors:
1) Parse error in the javascript file - that's understandable as I included the javascript file in header and the file gets executed before the php actually retrieves any data.
2) data_arrival method is undefined
How can I fix this ?? I want to pass the $tempdata (after its populated by php) to data_arrival method as an argument.
Thanks in advance !
First of all: it's PHP that's executed first, not JavaScript. It can't be the other way round in your example.
data_arrival is undefined... because either you haven't defined it at all, or because it is defined after it's called.
To pass the value from PHP to JavaScript in your case, you can use:
data_arrival(<?php echo $_tempdata; ?>);
It will generate something like:
data_arrival([a, b, c, d, ...]);
Of course, data_arrival function need to be defined prior to its execution.
Edit
And maybe it's good to use the same variable name: $_tempdata vs $tempdata.
This is a php file below named getques.php at server. In this php file, the variables subnm1, chpno1 and qnumber1 are posted from a html-javascript file from client side. With these, a database at server is accessed and the output of SQL query is stored in a variable $px.
<!DOCTYPE html>
<html>
<body>
<?php
$x = $_POST["subnm1"];
$y = $_POST["chpno1"];
$z = $_POST["qnumber1"];
$con=mysqli_connect("localhost","compete7_bhunia","pr393ss","compete7_iitmock");
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT question, optiona, optionb, optionc, optiond,
coroption FROM $x WHERE qnumber = $z AND chapno = $y");
while($row = mysqli_fetch_array($result))
{
$px = $row['question'];
}
mysqli_close($con);
?>
</body>
</html>
This $px is showing its desired data that has been retrieved from database. Now, I want that this variable $px should be passed to the same html-javascript file. How to get it at javascript. The relevant part is as below.
<script type="text/javascript">
var abc = "<?=echo $px ?>";
alert(abc);
</script>
This is not showing the value of $px. Pl. help.
Avoid using short open tags.May be in your php short open tags is not enabled. So try like this..
var abc = "<?php echo $px ?>";
short_open_tag directive) with PHP 5.3 or below (but since PHP 5.4.0,
Actually, in the php.ini-production file provided with PHP 5.3.0, they are disabled by default:
$ grep 'short_open' php.ini-production
; short_open_tag
short_open_tag = Off
So, using them in an application you want to distribute might not be a good idea: your application will not work if they are not enabled.
Use like this :
<?php echo $px ?>";
As others have stated, you have a syntax error, your output line should read like
var abc = "<?php echo $px ?>";
However, this is not safe (and don't use short open tags <?=, as they may be disabled in PHP < 5.4): consider that $px contains a double quote, then your syntax will be malformed; it is even possible to inject JavaScript code this way. Don't do this!
A safer method is to use json_encode:
var abc = <?php echo json_encode($px) ?>;
(Note that you don't need to surround this with quotes.)
On a side note, you are vulnerable to SQL injection. Please use prepared statements to prevent this.