PHP database user selection - php

Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !

You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.

Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);

Related

Difficulty in Fetching data for logged in user

Here is my login process, I want a same dashboard but data will be different for each user. But I am stuck with creating uid variables to get data for each login user.
if(isset($_POST['login_btn']))
{
$email_login=$_POST['email'];
$password_login=$_POST['password'];
$admin="admin";
$co_admin="co_admin";
$query = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$admin' ";
$query_run = mysqli_query($connection, $query);
$query_co = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$co_admin' ";
$query_run_co = mysqli_query($connection, $query_co);
if(mysqli_fetch_array($query_run))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $admin;
header('Location: index.php');
}
else if(mysqli_fetch_array($query_run_co))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $co_admin;
header('Location: company_view.php');
}
else
{
$_SESSION['status'] = 'Email ID / Password / User Type is Invalid';
header('Location: login.php');
}
}
Above source code is for separating Co-admin and Admin. Now Any Co-Admin login to the portal he should get his own details, I would like to know which function I have to call or how should I declare a uid variable to fetch data tables for each current logged in user. I found some other source codes but which is not related to me so i am confused with how I fix it with those code. Can anyone do it in my codes.
I think you are asking how to get data for the current user from mysql tables. Yes, the standard way of doing this is via a unique ID for each user that is pulled from the registered_users table, storing this in the session, and then referencing this in the other tables and filtering by this ID. I would not suggest storing anything else from this table in the session as the ID is likely to have a stronger guarantee of imutibility.
For example if you have a table of recently visited pages per user, you would get this via:
$query = 'SELECT * from recently_visited WHERE user_id = ?';
$stmt = mysqli_prepare($query);
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
You can check the mysqli documentation for how to then extract what you need from the executed statement. I've shown this example of a prepared statement so you can see how to avoid SQL injection as well.
You may want to look into using foreign keys to enforce this connection.

Display the item selected by specific user in status page for that specific user

I would like to ask how to display the information based username? I mean when I login, it will lead me to select data page. My select data page has username, name and date. The name is the name of item in spinner, i put these item in spinner. For example, username which is john select item 1 in spinner and it will send to database. Then when go status page, it will only display the item selected by John only in John account. Same as other account, in their account only will display their own item selected.
Below is my select item php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
$date = $_POST['date'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name, date) VALUES
('$username','$name', '$date')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Selected Successfully';
}else{
echo 'Sorry, You Already Select this item';
}
//Closing the database
mysqli_close($con);
}
?>
View Status Php:
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM Selection";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"username"=>$row['username'],
"name"=>$row['name'],
"date"=>$row['date']
)
);
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I am using localhost and phpmyadmin.
Table structure for Selection is below:-
id - primary key Not Null
username NOT NULL,
name NOT NULL,
date NOT NULL,
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
As you haven't mention the Schema of Spinner and Selection table, assuming a simple case for you, the solution would be like instructed below..
When user logs in, capture it's username (usually store it in session till he/she logs out).
In your Status.php your query would be
Select * from Selection where username = '$YOUR_USER_NAME_FROM_SESSION_HERE';
That should be enough as per your requirement.
NOTE: Using variable directly in your query will result in exposure of SQL injection. To prevent Sql injection, refer this answer too.
when the user logged in set the session using $_SESSION["name"] = "$username";
right now session is set then you can access the session variable from anywhere in the view page you retrieve the session using
$user= $_SESSION["name"].
now you fetch the items from the database
like
$sql = "SELECT * FROM Selection where username='$user'";
try it

Retrieving data from MySQL database using $_SESSION username

I am new at PHP and I'm trying to create a profile page whereby the user is able to view their information which they inserted when signing up to the website.
At first I'm attempting this with just their first name, so that whoever is logged in can see what first name they have saved on the database.
I have a included "checklog.php" page which includes
<? php session_start(); ?>;
And in my page, when i use;
echo $_SESSION['username']
The user's username is printed out fine.
So i've tried to apply this in mysqli query in order to print out their first name from the database like this;
<?php
if($db_server){
$query = "SELECT firstname FROM users WHERE username=$_SESSION['username']";
$result = mysqli_query($db_server, $query) or
die(mysql_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
echo $row['firstname'];
}
}
mysqli_free_result($result);
?>
But I get an error on line 15 which is the SQL statement, can someone tell me what I'm doing wrong in my statement?
First of all add session_start(); in the top of the PHP code..
<?php
session_start();//<-- Here
Second.. rewrite your query like this..
$query = "SELECT firstname FROM users WHERE username= '".$_SESSION['username']."'";

MySQL Insert/Update issue

So right now I'm working on a basic session system for my C# Application. I have a table with id,username, password and a session table with id, code, start.
the id columns of both tables are relative to the user logged in (id of user table is the same as session table). What I want to do is that when it sets the session it first checks to see if a session is already active, if it is then it will just update the current one, if there isn't one it will insert a new one. This works fine. My problem is that no matter what user I log in as the id is always set to 0 so I can have a max of one session active at a time.
Here is what I am currently doing:
//get id of inputted user.
$id = getUserId($username);
//first check if a session already exists that is connected to this username
$query = mysql_query("SELECT * FROM sessions WHERE(`id`='$id')") or die("Couldn't query database: <br> <br> " . mysql_error());;
if(mysql_num_rows($query) > 0) {
//session already exists, update it.
mysql_query("UPDATE sessions SET `code`='$code', `start`='$date' WHERE(`id`='$id')") or die("Failed to update session: <br> <br> " . mysql_error());
} else {
//session doesn't exist so lets create one
mysql_query("INSERT INTO sessions (`id`,`code`,`start`) VALUES('$id','$code', '$date')") or die("Failed to create session: <br> <br> " . mysql_error());
}
Also my getUserId function:
function getUserId($username) {
$query = mysql_query("SELECT * FROM users WHERE(`username`='$username')");
$row = mysql_fetch_row($query);
return $row[0];
}
My question, if you didn't get it already. Is why is it that the 'id' is always being set to 0 even though the getUserId() function is returning the proper id of the user?
Any suggestions?
Just found the mistake on my part.
I have this line which call the setSession function.
//set session
setSession($username. $password);
It is supposed to be only parsing the username, but I forgot tot take $password out. So when it is looking for the username 'user1' for example it will actually be looking for 'user1password' and therefore returning the 0 due to no records existing with those details.

How can i prevent a logged in user to delete post by others users?

I have a problem, I can not prevent a logged in user to delete post by others users?
In my code now, I can delete all users posts, but I want to be able to only delete my posts (the logged
in user posts).
Can somebody help me in the right direction on how to do that?
<div class="deletebtn">Delete post</div>
$id=$_GET['id'];
$sql="DELETE FROM shouts WHERE id='$id'";
$result=mysql_query($sql);
if($result)
{
echo('<div class="deletedpost">You have deleted a post. Tillbaka till Bloggen</div>');
}
else
{
echo "Something went wrong";
}
mysql_close();
Im using a href in one file, linking to another file where a use Sql code.
you can do this via session
check if user is logged in or not. if logged in then delete the post
if(isset($_SESSION['user']))
{
//delete post
}
Store userId in your table and update your delete query like this...
$sql="DELETE FROM shouts WHERE id='$id' and userId = '$_SESSION[user]'";
Check whether the logged in user is the owner for the particular post before deleting.
Write a select query with post id and owner id. If it returns true allow him to delete the post otherwise do not allow.
Don't you have a $_SESSION['id'] of sorts?
And you do have that user id associated in shouts table, so you know who's shout is it right?
DELETE FROM shouts WHERE id='$id' AND user_id='$_SESSION['id']'
You should treatthe inputs though.
use this kind of query, here it will delete only logged in user's post.
$sql="DELETE FROM shouts WHERE id='$id' and user_id = '$loggedin_session_id'";
I would suggest that upon the user signing up, you assign them a unique id (or let the database do it with auto increment) and save it in the database. Then, whenever they log in, you can pull that user_id from the database and store it in a session variable. When shouts are created, you store the user_id of the person who created the shout alongside the shout itself in the shouts table of the database. When a user attempts to delete a shout, you first check to make sure that that shout belongs to them before allowing them to delete it.
An example:
<?php
//when user logs in
$email = 'example#example.com';
$password = 'default';
$sql = "SELECT id FROM user_table WHERE email = '$email' AND password = '$password'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$_SESSION['user_id'] = $row['id'] //'id' is the user's id; assign it to the session variable
//user creates the shout
$user_id = $_SESSION['user_id']; //get the user_id from the logged-in user
$shout = $_POST['shout'];
$sql = "INSERT INTO shout_table (user_id, shout) VALUES ('$user_id','$shout')"; //store user id alongside the shout for future queries
mysql_query($sql);
//user about to delete the shout
$id = $_GET['id'];
$user_id = $_SESSION['user_id'];
//the sql to check in the shout_table to see if the shout they are deleting belongs to them
$sql = "SELECT * FROM shout_table WHERE user_id = '$user_id' AND id = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if ($row)
{
//everything is alright; this user can delete the shout, so prepare the DELETE query to do so
}
else
{
//the user is not allowed to delete the shout because it's not theirs; tell them so with an echo or whatever you're using for error handling
}
?>
The example above is rife with SQL injections. Validate and sanitize, of course. As well, mysql_query functions will be deprecated as of PHP 5.5, so get in the hang of using mysqli_query functions instead. Better yet, see if you can use PDO. :)

Categories