Difficulty in Fetching data for logged in user - php

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.

Related

Show username after posting (php/mysql)

I am working on a small community page where users will be able to post news, pictures, and comment on them. The problem where I am stuck is, whenever a user posts an entry, I want of course the username to be displayed next to the entry.
I am working with multiple tables here, one that stores the user info, and some that store the entry info (news, comments, pictures).
Now whenever a user posts something, I want to get his user ID out of the table USER, so that I can INSERT a new line INTO my table (in this case) NEWS, which wants the values Text, Title and U_ID as foreign key.
I am working with sessions, and since I had no problem simply displaying the name of the login user, I tried to use that user to select "his" row from the table and put the result into a variable ($uid) which I was hoping to use in another query for the INSERT INTO. However, according to the error message I get, something is wrong with my first query. Can anyone help?
<?php
include("dbconnect.php");
session_start();
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
$sqluser = "SELECT FROM USER USER_ID
WHERE Name = '$user'";
$userresult = $conn->query($sqluser) or die($conn->error);
while($row = $userresult->fetch_assoc()){
$uid = $row["USER_ID"];
}
} else {
header('Location: login.php');
}
if (isset($_POST["title"], $_POST["text"])) {
$title = mysqli_real_escape_string($conn, $_POST["title"]);
$text = mysqli_real_escape_string($conn, $_POST["text"]);
$sql = "INSERT INTO NEWS (Titel, Text, U_ID)
VALUES ('$title', '$text', '$uid')";
}
$conn->close();
?>
I think there is mistake in your query
$sqluser = "SELECT FROM USER USER_ID WHERE Name = '$user'";
It should be like this
$sqluser = "SELECT USER_ID FROM USER WHERE Name = '$user'";

PHP database user selection

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);

update column in mysql database when user logs in

I'm using this code to login user and I want to update the value in column loggedin to yes in mysql database. I tried to update it before sending header but it doesn't get updated. Where should I put the code to update the column?
if (isset($_POST['login']))
{
$username = trim(mysqli_real_escape_string($con, $_POST['username']));
$password = trim(mysqli_real_escape_string($con, $_POST['password']));
$md5password = md5($password);
// check user and password match to the database
$query = mysqli_query($con, "SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");
// check how much rows return
if (mysqli_num_rows($query) == 1)
{
// login the user
// get the id of the user
$fetch = mysqli_fetch_assoc($query);
// start the session and store user id in the session
session_start();
$_SESSION['id'] = $fetch['id'];
$_SESSION['username'] = $fetch['username'];
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE userid = 1;");
header("Location: message.php");
}
else
{
// show error message
echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
}
}
You're not updating the correct userid. You're updating userid = 1 instead of the ID belonging to the user who logged in. It should be:
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE id = {$_SESSION['id']};");
You need to change this:
UPDATE user SET loggedin = 'yes' WHERE userid = 1;
To this:
mysqli_query($con, 'UPDATE user SET loggedin = 'yes' WHERE userid = 1');
Please don't use the md5() function hashing passwords, it isn't safe, use these functions instead:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
You also use this:
if (mysqli_num_rows($query) == 1)
To check if the username exists, I suggest changing it to this:
if (mysqli_num_rows($query))
It does the same but you need less code to do it.
Other than that, please also learn how to prepare your queries before inserting them, your current code is vulnerable to SQL injection, more about that can be found here:
How can I prevent SQL injection in PHP?

Cannot login in PHP/MySQL

I've been modifying my code but I still can't log in... I have a MySQL database with a database called "users" with a table called "Users" and the following rows "UserNameID", "userName" and "password". I have created just an entry in order to test that:
+------------+----------+-----------+
| UserNameID | userName | password |
+------------+----------+-----------+
| 1 | root | pass |
+------------+----------+-----------+
Here my code:
<!DOCTYPE html>
<?php session_start(); ?>
<html>
<head>
<title>File1</title>
</head>
<body>
<?php
$DB_connection = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($DB_connection));
function SignIn() {
$usr = $_POST['user'];
$pw = $_POST['pwd'];
if(!empty($usr)) {
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } }
}
SignIn();
mysqli_close($DB_connection);
?>
</body>
</html>
When I introduce a wrong password or username, it gives me "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...". However, it throws me the same when I put the correct password and username. What is wrong in my code?
Thanks a lot!
There numerous issues here. There are scoping issues, you are using the wrong methods, it's unsafe.
First off, these 2 lines:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
That's not how you query a database. You only need to call either mysql_query or mysqli_query depending on what API you are using. You are using MySQLi in this case, so do this:
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
$result = mysqli_query($DB_connection,$query);
Second, your SignIn function can't access the $DB_connection variable, it's out of scope. You need to pass it in:
function SignIn($DB_connection){
}
SignIn($DB_connection);
Third, this code is very unsafe! Never use $_POST directly in an SQL query like that. You should never be concatenating variables into an SQL string, you should use prepared statements.
// Don't use "SELECT *", use the fields you want
$query = mysqli_prepare($DB_connection, 'SELECT user_id FROM Users where userName = ? AND password = ?');
// This sends the values separately, so SQL injection is a thing of the past
mysqli_stmt_bind_param($query, 'ss', $usr, $pw);
// Run the query
mysqli_stmt_execute($query);
// Prepared statements require to define exactly the fields you want
mysqli_stmt_bind_result($query, $user_id);
// Get the data
while(mysqli_stmt_fetch($query)){
echo $user_id;
}
mysqli_stmt_close($query);
Lastly, storing plaintext passwords is bad practice. Use a hashing library. PHP 5.5+ has one built-in (http://php.net/password). There's also a version for lesser PHP versions (https://github.com/ircmaxell/password_compat).
P.S. As pointed out in the comments (here's a link), your session_start() is in the wrong spot. That sends a header, so it requires that there be nothing echoed out before it.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
Make sure that there is no whitespace (or anything) before the session_start().
Your problem is here:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
This should instead be
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
You're then passing the query string rather than a resource to mysqli_query.
(Also, refer to Shankar Damodaran's answer regarding the scope issue: pass $DB_connection to the SignIn function).
As a side note, you shouldn't use posted data directly into the query. You're at risk of SQL injection. Look into sanitizing the data or, preferably, prepared statements.
First of all, you are running into scope issues here.
In this line...
$result = mysqli_query($DB_connection,$query);
The variable $DB_connection is not accessible inside your SignIn() and thus your query is getting failed. Also you are mixing mysql_* (deprecated) functions with mysqli_* functions.
This simple and small code snippet for the login might help you..
$con = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($con));
$username = $_POST['username'];
$password = $_POST['userpassword'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '$username' and user_password='$password'");
$count=mysqli_num_rows($result); // get total number of rows fetched. needs only 1 row for successful login.
if($count==1){
//Login successful
}
else{
//Login unsuccessful
}
It will fetch a row if the entered username and password are matched.It will fetch only one row as the username and password will be unique. If the count of rows fetched is '1' you can have successful login.

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