Deleting user posts, restrict delete to author of post - php

So right now, I've got a working PHP script that can delete posts from my network. But right now, everyone is able to delete everyones posts if they are logged in. I want restrict this to the authors of the posts, so they are only able to delete their own posts. How can I do this?
This is how my delete.php it looks like:
<?php
session_start();
if (empty($_SESSION['user_id'])) {
header('Location: index.php');
exit;
}
$user_id = $_SESSION['user_id'];
include "connect.php";
if(isset($_GET['id'], $user_id))
{
mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM posts WHERE id=".$_GET['id']);
mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE users SET posts = posts - 1 WHERE id='$user_id' ");
header("location: index.php");
}
mysqli_connect();
?>
In the main page where the posts are being displayed, the button is displayed like this:
Delete
It finds the postid itself. I have two tables, users and posts. Both has the column user_id, so the post table does get same user_id as in users_id.

First, your code is not safe!
Keep in mind that everyone can mess with your system when not escaping user input! You should read more about here
As you are checking already by the session if the deleting user is logged in, you now have to fetch the data from the deleting post (look for the post with the given post id in $_GET['id'] (ESCAPE IT!!!)) in table "posts". As you said, your table "posts" contains the field "user_id" and if you get this value you can simply compare it by the id given by $_SESSION["user_id"]

Related

MySql select statement with echo variable

I have mysql database with two tables. The primary table contains the user login details and the secondary table contains user activities. The tables are linked by the account numbers.
I have created registration page and sign in page where users register and login. Users are displayed with a home page with two buttons.
When users clicked on the button, it is supposed to run a query based on the user login credentials. The query looks like this:
$result = mysql_query("select mydate, preamount, currentdeposit,
debit, currentinterest, totalamount, status from NormalAccount where
acctnumber = '$actno'n ORDER BY mydate DESC LIMIT 5");
Because I need to filter based on the user account number, I have design a form where they will need to enter their account number again. This makes the whole process looks like double work and users are complaining about the whole process of entering information twice.
WHAT I WANT:
How do I write the query such that the query will populate the user credentials automatically so that they need not to enter their account number again before viewing their account details?
I have a session on the pages already that enables me to pull and display the user details on the page using echo such as echo acctname where it display the account name of the user in any part of the page.
I used the php with echo below to automatically display a welcome message to the users using the account name automatically. How to I integrate this code below
<?php echo $userRow['acctname']; ?>
into the WHERE clause in the main query so that it automatically populate the account name for the users so that it will filter the record based on their acctname?
I have a session on each page with this code:
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysql_query("SELECT * FROM userss WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>
Thanks.
Zollyzo
I'm not entirely sure that I understand the problem, but the first time that you ask for the account number, you could store it in the $_SESSION variable the first time you receive it from the user. Then, you could just retrieve it later, even if it's on a different page.
<?php
session_start();
...
//you get the account number somehow in $actno
$_SESSION['acctNr'] = $actno
...
//later in your code, or on another page that has had session_start() run
$actno = $_SESSION['acctNr']
//use it as you would before.
If the user has logged in successfully, save their account number (and maybe other details) in a session variable. You can use that session variable for your succeeding queries so you don't need to ask the users to enter their account number again.
Basic usage: https://www.w3schools.com/php/php_sessions.asp

SELECT rank FROM members WHERE?

I have written an SQL query and a $_SESSION cookie called "username" basically what I am trying to do is query the database for the "logged in" users rank that is contained in the "rank" column in the "members" table of my database.
Here is my header code to check that they are actually logged in (otherwise it redirects them to the login page)
session_start();
if (!isset($_SESSION['username'])) {
header("location:login/main_login.php");
}
AND Here is what I have so far for my query but I have absolutely no clue how to proceed in only selecting the user that is logged in. Note: I am aware that the query is not completed
$result = $conn->query("SELECT rank FROM members WHERE ");
$userrank = $result->fetchAll(PDO::FETCH_OBJ);
I've also set a variable for MyRank so that I can check the users rank to display specific content. (Not sure if that really matters in terms of my query but hopefully you get the idea.)
$MyRank = $userrank[1]->rank;
EDIT: additional information.
So basically I am trying to display content based on what the users rank is in my database. IE) if they are an administrator I want to show specific html. If they are a user I want to show a different set of html. How I'm doing it currently (that isn't working) is by a php if statement like so:
if ($MyRank == "Administrator"){
echo adminpanel();
}else if ($MyRank == "User") {
echo userpanel();
}
Basically the problem I'm having is that my User or Admin panels wont display unless ALL the users in my database are "Administrator" or "User". If there is an Administrator and a User in that table it will show nothing at all.
Based on guesses:
$authUser = $_SESSION['username']; // get the logged in user from session, guess this is the username
$result = $conn->query("SELECT rank FROM members WHERE username='$authUser';");
// if its userid then userid=$authUser without single quotes
$userrank = $result->fetchAll(PDO::FETCH_OBJ);

Get logged in memberID from database

I have two tables (blog_members and blog_posts) which are related 1 to many, 1 member to many posts. Therefore, in order to be able to relate the two I had to make one field in blog_posts named memberID and set up the relation between this field and the one from blog_members.
Now, I'm trying to make a script to add posts into the database. The thing is, now I have the field memberID in blog_posts which needs to be the same with the one from blog_members in order to be related. So, I'm trying to get the current logged in memberID from the blog_members so I can introduce it into the blog_posts.
I know this can be done with an input where you can type your ID but it doesn't feel right, I want this to be in the back, not to be seen.
Short story:
$memberID = get current logged in memberID from blog_members;
//insert into database
$sql="INSERT INTO blog_posts (memberID, postTitle,postDesc,postCont,postDate) VALUES('$memberID',$postTitle','$postDesc','$postCont','$postDate')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p>Added successfully!</p>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
Normally you would store the ID of the logged in user in a session:
$_SESSION['login_userid'] = // THE USER ID OBTAINED FROM LOGIN
Now it will be stored in the browser as $_SESSION['login_userid'] and you can just put this to the top of your code:
$memberID = $_SESSION['login_userid'];
On every page where you use sessions you must run session_start() before the first line of HTML code. If you are not sure how to create your own login system, have a look at this tutorial.
Note: memberID is not unique in the blog_posts table, as one user can create many posts. You should probably create a primary key blogpostID as well.

Retrieving data all rows where specific user_id is present?

I am working on a user profile page, and I have made it to where a user can post text and that will be uploaded to the "posts" database. That all works fine. But now I want to make it to where if a user goes to a users profile, it will echo out all their user posts. The database is laid out this way:
post_id user_id content
And I want to make it to where when a user lands on a user's page it grabs their $user_id and then forms a mysql_query and then echos out all of their posts that are present in the users database. What would be the best way to do this? Thanks
So far I have tried this:
mysql_result("SELECT * FROM posts WHERE user_id = $user_id");
You are doing right thing.
You have to just fetch all the data using the while loop.
like.
$res=mysql_query("SELECT * FORM posts WHERE user_id=$user_id");
while($row=mysql_fetch_assoc($res))
{
echo $row['post_id'];
}
You got my point?
// execute the query
$stmt = mysql_query("SELECT * FROM posts WHERE user_id ='".$user_id."'");
then fetch using different php functions used to fetch data and display..
while($row = mysql_fetch_array($stmt)){
echo $row['db_column_field'];
}

How do I create a user history?

I want to create a user history function that allows shows users what they done.
ex: commented on an ad, posted an ad, voted on an ad, etc.
How exactly do I do this?
I was thinking about...
in my site, when they log in it stores their user_id ($_SESSION['user_id'])
so I guess whenever an user posts an ad(postad.php),
comments(comment.php), I would just
store in a database table
"userhistory" what they did based on
whenever or not their user_id was
activate.
When they comment, I store the user_id in the comment dbc table, so
I'll also store it in the
"userhistory" table.
And then I would just queries all the rows in the dbc for the user to
show it
Any steps/improvements I can make? :)
Look at the statistics and logging section of media wiki schema. You can implement something similar to this.
http://upload.wikimedia.org/wikipedia/commons/4/41/Mediawiki-database-schema.png
Similarly, what you could do is have mySQL based logging, ie every page hit is logged in the mySQL database, which tracks the IP, userid, datetime and page requested.
Then for the page that you view history, you could have a script like this. This is just pseudo code, so take it at face value.
<?php
$actions = array('comment.php' => 'posted a comment', "postedad.php" => "posted an ad");
$query = mysql_query("SELECT * FROM logHits JOIN users ON users.id = logHits.userid WHERE loghits.userid = $userid");
while ($row = mysql_fetch_array($query)) {
echo $row['username']." ".$actions[$row['pagename']."<br />";
}
?>
Again, this is just pseudo code and you can most certainly improve the concept by it. You could possibly use a combination of printf();/sprintf(); and make it so, for example, "a comment" in the action text hyperlinks to the actual comment.
There are quite a few ways to go about this. This probably isn't the best way.
You could also just do an insert query to a table like userHistory whenever the persons does an action like you specified. This is probably the best way to go about it. You could have that able with fields like id, userid, actiontype, actionid
actiontype would be "comment" or so, and actionid would be the id of the posted entry. Then you could easily map actiontypes to the comment page (passing the actionid) to view the actual posted comment.

Categories