I am reading values from database and would like to store the values as a session object to be reused by the code. however, the code executes fine but does not store any values in the session storage.
JS code
$.getJSON("sessionstore.php", {"points": myjson}, function(data){
sessionStorage.user = data[0];
sessionStorage.usermail = data[2];
sessionStorage.supmail = data[4];
sessionStorage.repsupervisor = data[3];
sessionStorage.issupervisor = data[5];
});
php code
<?php
include 'mydbconn.php';
if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);
}
// decode the json data that is being passed
$usrname = $points->usrname;
$sql = "Select EmpName, EmpMail, RepSupervisor, SupMail, IsSupervisor from glusers where EmpName='$usrname'";
$result = $conn->query($sql);
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
};
echo $data[0];
die();
?>
There are no errors but the code does not execute.
Regards,
You are not outputting valid json. Note that $data[0] is a row of your result set - an array - so when you echo it in php you will output something like Array.
You need to change:
echo $data[0];
die();
to:
echo json_encode($data[0]);
die();
Edit: Also, you are fecthing associative arrays, so you would need to address them in your javascript as:
data.EmpName
data.EmpMail
// etc.
Related
I am writing a script the will a echo a json object with values from the datatable when a request is sent to that script with a particular id, I have been able to get the records of member in an array but when I encode it into a json it become empty automatically but when I serialize the object and echo I will get all my record. I want the response in JSON.
<?php
include '../classes/RegisteredMemberDAO.php';
if (isset($_GET['getMember'])) {
$members = RegisteredMemberDAO::getAllRegistedMember();
//echo json_encode(RegisteredMemberDAO::getAllRegistedMember());
$sql = "SELECT * FROM members";
$mysqli = db_connect();
$result = $mysqli->query($sql);
$members = array();
while ($row = $result->fetch_assoc()) {
$member = new RegisteredMemberDAO();
$member->setEmail($row['email']);
$member->setSn($row['sn']);
$member->setUsername($row['username']);
$member->setPlan($row['plan']);
array_push($members, $member);
}
$mysqli->close();
//echo serialize($member);
echo json_encode($members);
}
Normally this error happens if the result contains mixed encoding characters.
To fix it, use JSON_UNESCAPED_UNICODE as second parameter to json_encode function.
echo json_encode($members, JSON_UNESCAPED_UNICODE);
To check error occurred during json_encode put this code after json_encode.
echo json_last_error_msg(); // Print out the error if any
die(); // halt the script
<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
if($res) {
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['success']=true;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
$re = array();
while ($row = mysqli_fetch_assoc($query))
{
print_r($row);
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>
This is my full PHP code in this I need two json responses,
1> when I refresh the page
$sql="call regtask2('$userid')";
This query has to work and pass the response to the ajax, then I am using click button. When I use click button this query has to work and pass the response
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
I this is poosible?
3 options:
Just split your php code. On refresh, load script1.php and for your other ajax call, load script2.php.
You will need to set identifiers for your calls. In your ajax, add an "is_submit=true" to the query. In your php, check that value.
Assign your return value to $return and return that.
It's simple just add second query result to your previous json !, also consider adding some validation into user input to prevent sql injection
getting userid from $_POST is really bad idea
<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';
//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
$re = array();
if($res) {
$re['success']=true;
while($row = mysqli_fetch_assoc($res))
{
$array[]=$row ;
$re['userObj']['firstname'] = $row['firstname'];
}
}
else {
$re['success']=false;
}
if(isset($_SESSION['username']))
{
$sem=isset($_POST['sem'])?$_POST['sem']:'';
$fname=isset($_POST['fname'])?$_POST['fname']:'';
$year=isset($_POST['date'])?$_POST['date']:'';
$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
while ($row = mysqli_fetch_assoc($query))
{
$re['userObj'][]=$row;
//$options['userObj'][]=$row;
}
}
echo json_encode ($re);
return;
?>
I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author
I'm new to PHP and I don't understand why there is an extra word ARRAY infront of the JSON string.
Heres the output of JSON String:
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
This is the PHP file:
<?php
/*
* Following code will list all the Users
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all Users from Users table
$result = mysql_query("SELECT * FROM Users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Users node
$response["Users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$user[] = array();
$user["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// echoing JSON response
echo json_encode($response);
}
else {
// no Users found
$response["success"] = 0;
$response["message"] = "No Users found";
// echo no users JSON
echo json_encode($response);
}
?>
Remove
echo $response;
which is printing the word Array. If you try to echo the array, it will display the word 'Array' rather than printing the content of an array itself. Use print_r() function to display the content of an array.
print_r($response);
With the exception of classes that use the __to_string magic method, echo and print will only output the string interpretation of a variable's value. Number types (integers and floats), strings, and (I think) booleans have a straightforward string representation. Any other variable (arrays, objects, resources) will either output nothing, their variable type, or throw a fatal error.
For arrays and objects, print_r() will go through each member/property and attempt to convert it to a string (print_r being shorthand for print_recursive). So print_r($response) will give you the full array.
Bear in mind that generally the full array is only useful to output for debugging. Passing a php string version of an array to javascript is likely to be useless.
I am creating a game which uses the sharedObject to save each players progress locally. It also connects to a central database to create an online scoreboard. When a user inserts a score for the first time a unique ID is sent out of the database to the swf and saved as part of the sharedObject data.
Absolutely everything works and the ID is saved to the sharedObject, however when the swf is restarted the ID does not load (even though the other variables saved in the sharedObject do load).
I think it may be to do with the way it is formatted, perhaps to do with the XML but I'm not sure.
FLASH CODE
function saveGame(currID:Number) {
gameInfo.data["playername"+currID] = playername;
gameInfo.data["playerscore"+currID] = playerscore;
gameInfo.data["playerID"+currID] = playerID;
gameInfo.data["playerLevel"+currID] = playerLevel;
for(i=1; i<6; i++){
gameInfo.data["level"+i+"Score"+currID] = ["level"+i+"Score"];
}
gameInfo.flush();
}
function loadGame(currID:Number) {
playername = gameInfo.data["playername"+currID];
playerscore = gameInfo.data["playerscore"+currID];
playerID = gameInfo.data["playerID"+currID];
playerLevel = gameInfo.data["playerLevel"+currID];
}
function scoreboardSubmit() {
var insertReceive:XML = new XML();
insertReceive.ignoreWhite = true;
insertReceive.onLoad = function() {
playerID = this.firstChild.childNodes[0];
saveGame(currID);
};
insertSend = new LoadVars();
insertSend.playername = playername;
insertSend.playerscore = playerscore;
insertSend.playerID = playerID;
insertSend.sendAndLoad("scoreboardSend.php", insertReceive, "POST");
}
PHP CODE
<?php
$name = strip_tags($_POST['playername']);
$score = $_POST['playerscore'];
$id = $_POST['playerID'];
$con = mysql_connect("localhost","******","******");
mysql_select_db("******", $con);
if ($id == 0)
{
$insert="INSERT INTO scoreboard (Name, Score)
VALUES
('$name','$score')";
mysql_query($insert,$con);
$returnID = mysql_query("SELECT LAST_INSERT_ID()");
$playerID = mysql_result($returnID,0);
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
echo "<returnID>" . $playerID . "</returnID>\n";
}
else
{
$update = mysql_query("UPDATE scoreboard SET Name = '$name', Score = '$score'
WHERE id = '$id'",$con);
}
mysql_close($con);
?>
If I m understanding well, you shuld try to replace playerID by currID in your XML receiver object because atm you put the xml reply in a playerID var and the line after you call saveGame with currID as arg which is undefined.
function scoreboardSubmit() {
var insertReceive:XML = new XML();
insertReceive.ignoreWhite = true;
insertReceive.onLoad = function() {
var currID = this.firstChild.childNodes[0];
saveGame(currID);
};
insertSend = new LoadVars();
insertSend.playername = playername;
insertSend.playerscore = playerscore;
insertSend.playerID = playerID;
insertSend.sendAndLoad("scoreboardSend.php", insertReceive, "POST");
}
You should add the correct content type to your php page
header('Content-type: text/xml');
Finally I think it would be better to store your data in a different way (for exemple by using a savedgame object which contains all game related properties for a same currID)
Thanks for the answer but that wasn't the problem.
I think the problem was that when the sharedObject was having problems storing variable as true numbers and was just converting everything to strings, which was fine for the score but not for the Id as that had to be passed on to the PHP.
Solved it by using String('number') to convert the ID to a string to be stored in the sharedObject and then Number('string') to convert it back to a number when pulling it from the sharedObject.