I want to fetch a specific row from a table in my DB, i.e. 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.
Related
I've a webpage to a webinar with id 217, and to to verify if a user can watch the webinar, I use that function:
function user_verify($idlive, $register){
require("connect.php");
$query = "SELECT * FROM `users` WHERE idlive = 217 && register = '$register'";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
mysqli_close($conn);
if(isset($user)){
return 1;
} else {
return 0;
}
}
If return 1, I call the function to access the webinar:
function login($register){
require("connect.php");
$data_hora_inscricao = date('d/m/y H:i:s');
$query = "SELECT * FROM `users` WHERE register = '$register' && idlive = 217";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
mysqli_close($conn);
if(isset($user)){
$data = [
'u_id' => $user['id'],
'u_name' => $user['nome'],
'u_email' => $user['email'],
'u_level' => $user['level'],
'u_time' => 0
];
$dadosUserCookie = serialize($data);
setcookie('d_user_217', $dadosUserCookie, time() + (86400 * 1), "/");
return 1;
} else {
return 0;
}
}
If it returns 1 (success), I set a cookie to request user data on other pages. It always worked well, until yesterday. I don't know what's going on, but my AWS Lightsail database shows me that this code is using 100% of database capacity. What I can do to solve this?
While creating a group with user ids, I am checking if the entered id exists in database. If it exists, group should be created, if not it should pop out an error.
I am passing array with user ids to a function user_check, but it is not getting checked. Here is my code:
<?php
function user_check($user_id)
{
$u1 = mysqli_query($con, "SELECT uid from users where uid<>'" . $_SESSION['user_id'] . "'");
while ($row = mysqli_fetch_array($u1)) {
$users = $row['uid'];
echo "users" . $users;
$users1 = sort($users);
$users2 = sort($user_id);
printf($users1);
if ($user1 == $user2) {
echo "same";
} else {
echo "not same";
}
}
}
Given a list of user_ids (that you have validated/filtered already) you could write a function something like the following (untested):
function all_users_exist(array $user_ids, Mysqli $con)
{
$result_uids = [];
$ids = implode(',', $user_ids);
$sql = "SELECT uid from users WHERE uid IN ($ids)";
$result = $con->query($sql);
if($result)
while ($row = $result->fetch_array(MYSQLI_ASSOC))
$result_uids[] = $row['uid'];
sort($user_ids);
sort($result_uids);
return $user_ids == $result_uids;
}
I want show my message system user Profile name(If have) else show user name.
In my every code I used as below, which work well.
if (empty($pname)) $pname = $username;
But in below I cannot understand how to Return 'profile name else user name' in my "function getusername($userid)".
Here if I use return $row[0] at my "function getusername" Its show username, But I want to show Profile name and If profile name empty then show user name.
Get profile name/user name code:
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
} else {
return "Unknown";
}
}
This code fetch a specific message
function getmessage($message) {
$sql = "SELECT * FROM mail WHERE `id` = '".$message."' && (`from` = '".$this->userid."' || `to` = '".$this->userid."') LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
// reset the array
$this->messages = array();
$row = mysql_fetch_assoc($result);
$this->messages[0]['id'] = $row['id'];
$this->messages[0]['title'] = $row['title'];
$this->messages[0]['message'] = $row['message'];
$this->messages[0]['from'] = $this->getusername($row['from']);
$this->messages[0]['to'] = $this->getusername($row['to']);
} else {
return false;
}
}
Use this
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $pname;
} else {
return "Unknown";
}
}
The problem is with how you are returning the value.
Change:
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
To:
if(empty($pname)) return $username;
else return $pname;
Also, it is suggested you use mysqli instead of mysql.
Can't you use something like this?
return isset($pname) ? $pname : $username;
This basically is: if $pname is set, then return $pname, else return $username
So I'm making a usergroup function that allows me to block off pages to lower user levels. This is my function for grabbing info:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result-fetch_assoc()){
$info = $row[$requested_info];
return $info;
}
}
Right here:
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
is where something is going wrong. This is my method for grabbing the info:
$id = $_SESSION['user_id'];
$rank = grab_info($id, 'rank');//Gets rank from our id
$meets = can_access($rank, 4, true);//We're saying our user has a rank of 1 to access this page you need a rank of 3 and only 3 hence strict
if ($meets == false){//user cant access page
header("Location: index.php");
die();
}
Basically, it just keeps giving me the "There as a query error for some reason handle your query error" and I'm stuck. New to php so sorry if it's messy.
Using prepared statements and cast the variable as an integer.
$stmt = $con->prepare("SELECT * FROM `users` WHERE `id` = ?");
$stmt->bind_param("i",$id);
$id = (int) $_SESSION['user_id'];
$stmt->execute();
$result = $stmt->get_result();
Check to make sure that $id is actually set. If it's null that will cause your query to explode.
$sql = "SELECT * FROM `users` WHERE `id`='{$id}'";
Try this :)
$query=mysql_query("SELECT * FROM user WHERE user_email='$user_email');
Please try this:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM users WHERE id =". $id;
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result->fetch_assoc()){
$info = $row;
return $info;
}
}
Sorry about the last post I had. Here's my revision, please help me.
<?php
//connect database
$sql = "SELECT * FROM user where user_id = 8320 AND password = 'admin' ";
$query = pg_query($sql);
var_dump($row = pg_fetch_array($query)); //dumps correctly.
?>
BUT THE PROBLEM IS THIS..when I try to make it as a function LIKE:
function check($user_id, $password)
{
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($sql);
$row = pg_fetch_array($query);
return $row;
}
AND CALL IT HERE:
var_dump($data = check(8320, 'admin')); DUMPS NULL;
How come it ended up like this?
Its returning NULL because there is an error with your SQL query, and no results are being returned. You should do some error checking in your function, try this version:
function check($user_id, $password)
{
$dbconn = pg_connect("host=localhost dbname=test");
$sql = "SELECT * FROM user where user_id = $1 AND password = $2 ";
$result = pg_query_params($dbconn, $sql, array($user_id,$password));
$row = pg_fetch_array($result);
if (!$row) {
echo pg_last_error($dbconn);
} else {
return $row;
}
}
Try the code below. It should work fine for you.
$data = check(8320, 'admin');
var_dump($data);
Seems like your PostgreSQL resource is missing inside the function. You have two options.
Declare the connection resource inside the function using global.
Establish the connection inside the function.
This is the first option:
$conn = pg_connect('host','user','pass','db');
function check($user_id, $password)
{
global $conn;
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
And this is the second option:
function check($user_id, $password)
{
$conn = pg_connect('host','user','pass','db');
$sql = "SELECT * FROM user where user_id = $user_id AND password = '$password' ";
$query = pg_query($conn, $sql);
$row = pg_fetch_array($query);
return $row;
}
According to the PHP manual, You may omit connection resource, but it is not recommended, since it can be the cause of hard to find bugs in scripts.