Show username after posting (php/mysql) - php

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'";

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.

User gets logged out, after post upload [PHP]

I got a problem with my post upload formula and need your help.
With this formula, I inserted data into 2 tables at same time and it worked perfectly fine. My next step was to insert the userid in the post table, so that the post is linked to the creator of the post.
Inserting the userid in the post table worked as well but after the upload, the user gets logged out.
Here is a part of my code
(I marked the code where I think there is something wrong with a "X")
session_start();
$db = mysqli_connect("localhost", "root", "", "abc");
if (isset($_POST['upload_post']))
{
$ad_post_title = mysqli_real_escape_string($db, $_POST['post_title']);
X $user_id = $_SESSION['id_u'];
X $_SESSION['id_u'] = mysqli_insert_id($db);
X $sql_p = "INSERT INTO ad_posts (post_title, user_id) VALUES ('$post_title','$user_id')";
if (mysqli_query($db, $sql_p))
{
$ad_post_id = mysqli_insert_id($db);
...
}
}
Maybe I have done something wrong with the session?
On the second line of your code you are overwriting a session variable of the users id, which I figure you're using to make sure the user is logged in, with the id of the newly inserted row.
$user_id = $_SESSION['id_u'];
X $_SESSION['id_u'] = mysqli_insert_id($db);
$sql_p = "INSERT INTO ad_posts (post_title, user_id) VALUES ('$post_title','$user_id')";
In the code you supplied I do not see are reason for this second line, remove it and your user won't be logged out, unless of course you're overwriting it somewhere else also.
You cannoT use mysqli_insert_id() before add data in the system.
I checked same code in my system and its working fine.
session_start();
$db = mysqli_connect("localhost", "root", "", "abc");
if (isset($_POST['upload_post']))
{
$ad_post_title = mysqli_real_escape_string($db, $_POST['post_title']);
$user_id = $_SESSION['id_u'];
$sql_p = "INSERT INTO ad_posts (post_title, user_id) VALUES ('$post_title','$user_id')";
if (mysqli_query($db, $sql_p))
{
$ad_post_id = mysqli_insert_id($db);
...
}
}

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

How do I find out a specific row ID from a table?

Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);

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