I have a page which shows the comments posted by all users. Here I need to show a delete link on the side of the comments posted by that current logged in user and he should be able to delete that comment too (like in Facebook, Orkut or any Blogging site). The sample code which I have tried is:
<?php
$user_id = 1;
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("blog", $con);
$result = mysql_query("SELECT * FROM replies");
while($row = mysql_fetch_array($result))
{
$replies = $row;
if($replies['poster_id' == $user_id]){
$delete = 'Delete';
}
echo $replies['poster_id']?></a> ¦ <?php echo $replies['reply_text']?> ¦ <?php echo $delete?></div>
<?php echo "<br />";
}
mysql_close($con);
?>
Here I have given the user_id which is hardcoded here. What I got is, delete link is displayed on all comments. I need to display delete link for user_id with "1" only. Can anyone suggest me to get the solution...Thanks in Advance...
if($replies['poster_id' == $user_id]){
need to be
$delete ='';
if($replies['poster_id'] == $user_id){
$delete = 'Delete';
}
you need to unset the $delete variable in every loop, if not once its get a value and present it in every cycle of loop
Related
I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>
after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to
I’m working on a blog website where the idea is that the current user that is logged in can edit and delete their own posts. I finally got it to work, but my question is how I can prevent that a user can write the following input in the URL and do the same actions as my delete.php action.
(Example) Manual URL input with topic_id:
/delete.php?del=133
Do anyone know how I can edit my existing code or know a better solution to the problem I will be much grateful!
This is how my code looks:
Profile.php:
if (#$_GET['id']) {
$check_d = mysql_query("SELECT * FROM users WHERE id ='".$_GET['id']."'");
while ($row_d = mysql_fetch_assoc($check_d)) {
echo "<div class='spacer'></div><h2 class='headertext'>Inlägg skapade av : ".$row_d['username']."</h2>";
$check_u = mysql_query("SELECT * FROM topics WHERE topic_creator='".$row_d['username']."' ORDER BY topic_id DESC");
while ($row_u = mysql_fetch_assoc($check_u)) {
$id = $row_u['topic_id'];
echo "<tr>";
echo "<td class='postmain'><a href='topic.php?id=$id' class='links'>".$row_u['topic_name']."<br /></a></td>";
echo "<td class='postmain'><p class='text'>".$row_u['topic_creator']."</p><br /></td>";
echo "<td class='postmain'><p class='text'>".$row_u['date']."</p><br /></td>";
if($_SESSION['username'] === $row_u['topic_creator']) {
echo "<td class='postmain'><a href='edit.php?edit=$id'><button>Redigera</button></a>";
echo "<a href='delete.php?del=$id'><button>Ta bort</button></a></td>";
}
echo "</tr>";
}
}
}
The highlighted code shows that only the current session (user) who made the post can edit and delete their own posts.
Delete.php:
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
//deleting the row from table
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
//redirecting to the display page
header("Location:admin.php");
}
Using isset function is solution here . The isset function will check that whether user clicked the delete/modify link or not(i.e he pasted delete.php directly in link) . So your code will only execute when user clicks the link .
if (isset($_GET['del']))
{
// your profile.php code here
}
else
{
// error message
}
You can use the same $_SESSION logic to ensure anyone accessing the delete.php has the appropriate permissions.
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
// Get the author for the specified post to ensure they are permitted to do so
// TODO
// Check that the author is the same as the $_SESSION user
if($_SESSION['username'] === $postAuthor) {
//deleting the row from table - FIX THIS (see below)
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
} else {
// User is not authorized, create error handling
// TODO
}
//redirecting to the display page
header("Location:admin.php");
}
Unrelated, beware of SQL injection. Bobby Tables is a good guide and you should not be using the mysql_ functions and should be using prepared statements.
I need to check a database value assigned to a user account and redirect when loading a page if the value is 0 (or less than 1?)
code is have for the function is:
// ******************************************************
// JAY CHECK SCREENINGS FUNCTION
function CheckScreenings() {
if (!empty($_SESSION['userId'])) {
$conn = connectToDB();
if (!$conn) { die('Could not connect: ' . $conn->errorInfo()); }
$checkquery = ("SELECT screenings FROM screener_users WHERE user_id = '" . $_SESSION['userId'] . "';");
foreach ($conn->query($checkquery) as $row)
{
$screenings = $row[0];
}
if ($screenings == 0)
{
header("Location: http://example.com/myOtherPage.php");
die();
}
}
}
// ******************************************************
I also, on another page need to hide 2 hyperlinks if this same value is 0.
<li>
Take a new test
</li>
<li style="margin-bottom: 20px;">
<?php $lastTest = getUserLatestIncompleteTest($user_id); ?>
Continue last incomplete test
</li>
Any ideas?
Thanks,
J
If your functions do what I think they do, something written like
$result_rows = $conn->query($checkquery);
if (count(result_rows) == 0) {
header("Location: http://example.com/myOtherPage.php");
}
Should work.
Im blocked at following part of code...
i have config.php page, with following code inside:
<?php
// Start the session (pretty important!)
session_start();
// Establish a link to the database
$dbLink = mysql_connect('localhost', 'USER', 'PASS');
if (!$dbLink) die('Can\'t establish a connection to the database: ' . mysql_error());
$dbSelected = mysql_select_db('DATABASE', $dbLink);
if (!$dbSelected) die ('We\'re connected, but can\'t use the table: ' . mysql_error());
$isUserLoggedIn = false;
$query = 'SELECT * FROM users WHERE session_id = "' . session_id() . '" LIMIT 1';
$userResult = mysql_query($query);
if(mysql_num_rows($userResult) == 1){
$_SESSION['user'] = mysql_fetch_assoc($userResult);
$isUserLoggedIn = true;
}else{
if(basename($_SERVER['PHP_SELF']) != 'index.php'){
header('Location: index.php');
exit;
}
}
?>
Now i have another page, with following code inside:
<?php include_once('config.php'); ?>
<?php foreach($_SESSION['user'] as $key => $value){ ?>
<li><?php echo $key; ?> <strong><?php echo $value; ?></strong></li>
<?php } ?>
That code show me all informations stored in database, one by one..
I want to show informations, individualy in my page, something like:
<?php echo $email; ?>
etcetera..
Can someone explain me how to do that?
Thank you
You should output it like
<?php echo $_SESSION['user']['email'] ?>
assuming that 'email' is the column name in the users table.
Just address the relevant field in the associative array:
<?php echo $value['email';?>
Use this in the config file:
$_SESSION['user']['email'] = mysql_fetch_assoc($userResult);
instead of this
$_SESSION['user'] = mysql_fetch_assoc($userResult);
in your code. You can pass as many columns you want to pass from your table.
And in another page use
foreach($_SESSION['user']['email'] as $key => $value)
instead of
foreach($_SESSION['user'] as $key => $value)
in your code.
Remember number of columns you pass in config file, all those columns should be called in this page.
I'm really struggling with this now for a while and can't seem to get it working. In members.php (where I show all the registered users) I have a list printed out with a link "ADD TO FRIENDS" next to each user.
I managed, for testing purposes to display each members id well (so it gets the ID) but when I click the link it directs to the friends.php where it seems the fault is in. I don't know how to get that friend's id I clicked on IN THE friends.php file. Please have a look!
members.php
<?php
include 'connect.php';
include 'header.php';
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> to view all the <b>registered</b> members.';
echo '<br/><br/>';
}
else
{
echo '<h2>Registered users:</h2>';
$sql = "SELECT * FROM users ORDER BY user_name ASC";
$result = mysql_query($sql);
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
//$name = mysql_result($result,$i,"user_name");
//$id = mysql_result($result,$i,"user_id");
//$picture = mysql_result($result,$i,"pic_location");
//?friend_id="'. $id .'
while($user = mysql_fetch_array($result)){
echo $user['user_name'].'<br/><br/>ADD TO FRIENDS<br/>';
echo $user['user_id'];
echo '<br/><br/>';
}
$i++;
}
///////////////////////////////
/// adding users as friends ///
///////////////////////////////
//while($user = mysql_fetch_array($result))
//echo $user['user_name'].'
//ADD TO FRIENDS<br/>';
//NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER
}
include 'footer.php';
?>
As I said I'm not sure how to get this so please have a look! Thanks!
J
friends.php
<?php
include "connect.php";
include "header.php";
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> if you want to add the person as a friend!';
echo '<br/><br/>';
}
else
{
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
//friend_id is the ID of the friend that is clicked on...
//HOW DO I GET THAT ID THAT IS CLICKED ON IN THE WHILE "loop" in members.php?
$friends = ("INSERT INTO friends SET user_id='" . $_SESSION['user_id'] . "', friend_id='".$id."', status='0'");
$result_friends = mysql_query($friends);
if(!$friends)
{
//When you can't add this person as a friend this error will show!
echo 'You cannot add this user at this time. Please try again later!';
}
else
{
//When the friend is now added to the system!
echo 'Great! Now the user needs to approve before you can be friends!';
}
}
?>
On your friends.php use
$_GET['user_id']
Instead of $id, $id is undefined, to get the value of id from the query string you call it using an $_GET variable like,
$_GET['name_of_query_string_value']