I want to fetch a specific row from a table in my DB, ie only what's pertinent to the user that's logged in. I'm using the following script for this:
<?php
include('./classes/DB.php');
include('./classes/Login.php');
$connect = mysqli_connect("localhost", "root", "", "gaming");
$playerid = Login::isLoggedIn();
$sql = "SELECT * FROM games";// WHERE player_id =" .$playerid;
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
if ($row['player_id']==$playerid) {
$json_array[] = $row;
}
}
echo json_encode($json_array);
?>
Login.php:
<?php
class Login {
public static function isLoggedIn() {
if (isset($_COOKIE['CHEZA'])) {
if (DB::query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['CHEZA'])))) {
$userid = DB::query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['CHEZA'])))[0]['user_id'];
if (isset($_COOKIE['CHEZACHEZA'])) {
return $userid;
} else {
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
DB::query('INSERT INTO login_tokens VALUES (\'\', :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$userid));
DB::query('DELETE FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['CHEZA'])));
setcookie("CHEZA", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie("CHEZACHEZA", '1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
return $userid;
}
}
}
return false;
}
}
?>
I get the desired response in my browser but when I use a REST client all I get is an empty array [ ]. What am I doing wrong?
$playerid = Login::isLoggedIn();
is not set, check it.
EDIT
Now the code of isLoggedIn()
is published: are you sure your REST client is sending the CHEZA cookie? I don't think it is a good idea to use cookies in REST call. I found useful this reading: https://softwareengineering.stackexchange.com/questions/141019/should-cookies-be-used-in-a-restful-api
Try modifying your php code to this, I have added an isset check before running your query and logic code :
<?php
include('./classes/DB.php');
include('./classes/Login.php');
$connect = mysqli_connect("localhost", "root", "", "gaming");
$playerid = Login::isLoggedIn();
if(isset($playerid)){
$sql = "SELECT * FROM games WHERE player_id =" .$playerid;
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
if ($row['player_id']==$playerid) {
$json_array[] = $row;
}
}
echo json_encode($json_array);
}
?>
if it doesn't works, try adding a print_r($playerid)
and check if you are getting the loggedin user id.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.