PHP: Flagged Comments - php

I'm implementing a flag comment system on my blog, currently have this code for it:
<form method="POST">
<?php
$con=mysqli_connect("localhost","root","admin","MyDatabase");
$sql = mysqli_query($con, "SELECT id, username, comment_body, user_id, DATE_FORMAT(date_created, '%M %d %Y') AS date_created FROM news_comments WHERE entry_id = '" . $entry_id. "'");
?>
<?php while ($comment = mysqli_fetch_array($sql)) { ?>
<table class="table">
<thead>
<tr>
...
</tr>
<td>
<?php echo $comment['username']; ?>
</br>
<?php echo $comment['comment_body']; ?>
</br>
<?php echo $comment['date_created'];?>
</td>
...
<td>
<button name = "report">Report</button>
<?php if(isset($_POST['report'])) {
$id = $comment['id'];
$conn=mysqli_connect("localhost","root","admin","MyDatabase");
$sqli = mysqli_query($con, "UPDATE news_comments SET isFlagged = 1 WHERE id = '$id'");
} ?>
</td>
....
</table>
It works, but when the report button is clicked, it flags all comments on the page. How can I change this so it's just the one specific comment?
Thanks

This is happening because you have your flagging logic in the while loop. Whenever a user clicks the Report button every condition where if(isset($_POST['report'])) is triggered - which would be all the comments.
You have to move the condition out of the loop (typically the top of the page), and then send the id of the post you want to flag as it will no longer be part of the loop.

Related

Delete a line from a table in PHP

i'm currently working on an admin which permit to the user who has the rights to delete any account with a button, and all the accounts are displayed in a table and stored in a database (i'm using MySQL). For each row of the , there is a delete button, and i would like that, by pressing the button of the choosed row, it delete the account of the row selected. I dont really know how to do it clearly that's why I ask.
Can someone explain me the approach that i should take and give me an idea.
Have a good day.
[the admin pannel screen][1]
Here is where I am in my code :
<?php
require_once('testadmin.php');
if(!$isAdmin) {
header('Location: index.php');
}
include_once('./includes/head.php');
include_once('./includes/nav.php');
require_once('./lib/db.php');
// users
$stmt = $db->prepare('SELECT * FROM users');
$stmt->execute();
$users = $stmt->fetchAll();
?>
<main>
<table id="usersTable">
<h1 style="text-align: center;margin-top: 25px;">Users</h1>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th> </th>
</tr>
<?php
foreach ($users as $user)
{
echo
'<tr>
<td>'.$user['id'].'</td>
<td>'.$user['username'].'</td>
<td>'.$user['email'].'</td>
<td>'.$user['role'].'</td>
<td><button class="btn-danger" onclick=\'return confirm("Confirm account delete?");\'>
Delete account</button></td></tr>';
}
echo "</table>";
?>
delete.php :
NOTE : this is actually for delete the current connected account.
<?php
require('./lib/db.php');
session_start();
if(empty($_SESSION['user'])){
header('Location: login.php');
}
$user = $_SESSION['user'];
$req = $db->prepare('DELETE FROM users WHERE id=:id');
$req->bindValue(':id', $user["id"], PDO::PARAM_INT);
$req->execute();
unset($_SESSION['user']);
session_destroy();
header('Location: index.php');
Pass the identifier for the record to the delete.php page:
<a href="delete.php?id=' . $user['id'] . '" class="delete" style="color: #fff">
Then in delete.php you can reference $_GET['id'] and use that value in your SQL query to delete that specific record.
Note of course that within delete.php you'll probably want to make sure the current user is authorized to delete that record.

HTML PHP database - edit/delete button - passing value

im rather amateur with php and even more so with js. I have created a database table with an edit & delete button, as shown in the screenshot. (if anyone is also able to see why there is a gap between my header and body of table that would be great, i have no clue why this is cropping up, doesnt seem to be css).
The idea is to just click the delete button, pass the 'AwbNo' over to the delete.php page in order to delete the entire row from the database, and then automatically return to the page to see the updated table, if redirection can be avoided, even better just to make the operation smoother. Any help would be greatly appreciated, hope my code below is enough for aid
so select a row to delete>click delete>confirmation>row deleted from db. That is the process i am aiming to achieve
example database screenshot
<table class="table">
<thead>
<tr>
<th>Awb Number</th>
<th>Vessel</th>
<th>Client</th>
<th>Pieces</th>
<th>Total Weight</th>
<th>Carrier</th>
<th>Sender</th>
<th>Status</th>
<th>Arrival Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php //BEGINNING OF PHP
include("login/dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$sql="SELECT AwbNo, VesselName, ClientCode, Pieces, Weight, Carrier, Sender, Status, DATE_FORMAT(ArrivalDate, '%d-%m-%yyyy') FROM tbl_import";
$result = mysql_query($sql) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
echo "<p>There are $num_rows records in the Customer table.</p>";
echo "<table class=\"table\">\n";
while ($get_info = mysql_fetch_array($result))
{
echo ("<tr>\n");
echo ("<td>".$get_info["AwbNo"]."</td>");
echo ("<td>".$get_info["VesselName"]."</td>");
echo ("<td>".$get_info["ClientCode"]."</td>");
echo ("<td>".$get_info["Pieces"]."</td>");
echo ("<td>".$get_info["Weight"]."</td>");
echo ("<td>".$get_info["Carrier"]."</td>");
echo ("<td>".$get_info["Sender"]."</td>");
echo ("<td>".$get_info["Status"]."</td>");
echo ("<td>".$get_info["ArrivalDate"]."</td>");
?>
<td>
<div id="outer">
<div class="inner"><button type="submit" class="msgBtn" onClick="goToURL()" > Edit </button></div>
<div class="inner"><button type="submit" class="msgBtn2" onClick="goToURL1()"> Delete </button></div>
</div>
</td>
<?php
echo ("</tr>\n");
}
echo "</table>\n";
mysql_close();
?> <!--END OF PHP-->
</tbody>
</table>
Below is the js script to redirect user page when clicking on the 'edit' or 'delete' button.
<script>
function goToURL() {
window.open('php/edit.php');
}
function goToURL1() {
window.open('php/delete.php');
}
</script>
And below is the supposing 'delete.php' page to delete the record from the db on a live server, this is only an example, im not exactly sure if it is correct.
<?php
include("dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$AwbNo=$_POST['AwbNo'];
$sql="DELETE FROM tbl_import where AwbNo=$AwbNo";
mysql_query($sql)or die("Delete Error: ".mysql_error());
mysql_close();
echo "Record was successfully deleted.\n";
?>
The issue your having is because you need to pass the primary key that AwbNo in you case, along with the Edit /Delete link, so that the correct record is selected from DB. This is not happening in your case.
The code for the table needs to look something like mentioned below for the edit & delete links.
echo '<td>&nbspEdit&nbsp</td>';
echo '<td>&nbspDelete&nbsp</td>'
Also add this script in same page.
<script>
function delete_user(uid)
{
if (confirm('Are You Sure to Delete this Record?'))
{
window.location.href = 'delete.php?id=' + uid;
}
}
</script>
delete.php can have just this code:
<?php
include("dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$id = $_GET['id']; // $id is now defined
mysqli_query($conn,"DELETE FROM tbl_import where AwbNo='".$id."'");
mysqli_close($conn);
header("Location: index.php"); //redirect to relevant page
?>

Delete row from MySQL table when I press button Delete

I need to make cancel booking of room for one user who can see all his room booked.
The problem is It shows the booked room for the user, but the delete button did not work correctly.
I have snapshot of my db here and screenshot here.please any help?
Thanks.
Here is my php code for show booking data and the delete part in manage.php
<?php
session_start();
$connection = mysqli_connect('localhost', 'root', '', 'webapp');
global $connection;
$user_id="";
if(!isset($_SESSION['login_ID'])) {
header('Location: login.php');
die();
} else {
$user_id= $_SESSION['login_ID'];
}
$secondQueryStmt = "SELECT * FROM `booking` where UserID='".$user_id."'";
$query = mysqli_query($connection, $secondQueryStmt);
if(isset($_POST['BookingID'])) {
$boking_id = $_POST['BookingID'];
if(isset($_POST['delete_id'])){
$query = mysqli_query($connection, "DELETE FROM booking where BookingID= '".$boking_id."'");
}
}
?>
here is my form html in the same page also.
<article id="content" style="height:810px; background-color:white">
<div class="box1">
<!--content herer-->
<table class="wrapper" style="text-align:center">
<tr>
<th class="track animated fadeInUp">Room</th>
<th class="title animated fadeInUp">Quantity</th>
<th class="speaker animated fadeInUp">CheckIn Date</th>
<th class="day animated fadeInUp">CheckOut Date </th>
<th class="time animated fadeInUp"></th>
</tr>
<?php while($fetcher = mysqli_fetch_array($query)): ?>
<tr>
<td><?=$fetcher['Type']?></td>
<td><?=$fetcher['Quantity']?></td>
<td><?=$fetcher['CheckInDate']?></td>
<td><?=$fetcher['CheckOutDate']?></td>
<td><td><form action="manage.php" method= "post" />
<input type="hidden" name="b_id" value="<?=$fetcher['BookingID'] ?>"/>
<input type="button" class="btnSm hvr-fade lightRed" name="delete_id" value="Cancel Booking"/>
</form></td></tr>
<?php endwhile; ?>
</table>
</div>
</article>
Look at this statement here,
<input type="hidden" name="b_id" value="<?=$fetcher['BookingID'] ?>"/>
^ you've named it b_id, not BookingID
So change
$boking_id = $_POST['BookingID'];
to
$boking_id = $_POST['b_id'];
And use mysqli_affected_rows() function to check how many rows are affected from this UPDATE operation.
Here's the reference:
http://php.net/manual/en/mysqli.affected-rows.php
So your code should be like this:
// your code
$query = mysqli_query($connection, $secondQueryStmt);
if(isset($_POST['delete_id'])){
$boking_id = $_POST['b_id'];
mysqli_query($connection, "DELETE FROM booking where BookingID= '".$boking_id."'");
if(mysqli_affected_rows($connection)){
// success
}else{
// failure
}
}

$_GET does not work and query the property

I have a problem with $_GET method. I have retrieved some data about admins of a webpage from database & I added a hyperlink for users to get the information about that them.
Here's the code in my 1st page:
<?php if(($adminlevel)==1){
echo '
<h4 class="widgettitle">List of admins</h4>
<table class="table responsive">
<thead>
<tr>
<th>Admin Level</th>
</tr>
</thead>
'; getAdmins(); echo '
</table>
';
}else{
echo '<h4 class="widgettitle">You dont have permission to see this table</h4>';
}
?>
<div class="divider15"></div>
The function getAdmins() goes like this:
<?php
function getAdmins(){
global $con;
$get_admin = "select * from admins order by id";
$run_admin = mysqli_query($con,$get_admin);
while($row_admin = mysqli_fetch_array($run_admin)){
$id_admin = $row_admin['id'];
echo "
<tbody>
<tr>
<td>Trident</td>
<td class='center'><a href='editlevel.php?id=$id_admin' title='Clik to change admin level' target='_blank'>$adminlevel_admin</a></td>
</tr>
</tbody>
";
}
}
?>
As you see I link the users from my first page to another page which is called editlevel.php by the function getAdmins().
Therefore I made my hyperlink like this:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
And Here's the editlevel.php page:
<body>
<?php
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
$get_result = "select * from admins where id='$result_id'";
$run_result = mysqli_query($con,$get_result);
while($row_result= mysqli_fetch_array($run_result)){
$id_target = $row_result['id'];
$username_target = $row_result['username'];
$adminlevel_target = $row_result['adminlevel'];
$email_target = $row_result['email'];
echo '
<div class="mainwrapper">
<div class="header">
'; include "php/php_includes/overall/header.inc.php"; echo'
</div>
<div class="leftpanel">
';include "php/php_includes/overall/leftpanel.inc.php"; echo '
</div><!-- leftpanel -->
<div class="rightpanel">
'; include "php/php_includes/gadgets/rightpanel.editlevel.php"; echo '
</div><!--rightpanel-->
</div><!--mainwrapper-->
';
}
}
?>
</body>
So basically I used if (isset($_GET['id_admin'])){ to get the results of the item which user clicked & try to retrieve the data of that item from database via that.. But the problem is nothing appears at my screen. No error message & no result. Please if you know how can I solve it please let me know!
It appears that your link is:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
When it should be:
<a href='editlevel.php?id_admin=$id_admin'>$adminlevel_admin</a>
In order for it to work with:
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
Edit: It goes without saying, you should never trust user input (such as $_GET). These values should be validated and sanitised before being used in SQL queries.

Displaying user info on a page using their ID

Im trying to create a dynamic web page in php and mysql. I have the below code on the profile.php page. The issue im having is on the "while" line im not sure how i would go about getting the information from the DB. I want to display details like email, country First name, etc. Any help appreciated. Thanks in advance!
CODE:
$userid = (isset($_GET['id']) ? $_GET['id'] : NULL);
if ($userid) {
$userinfo = $DB->query_first("SELECT * FROM `users` WHERE `id` = '$userid'");
print_r($userinfo);
}
//{
while($row = sql_fetch_assoc($DB)){
echo'<div class="container">
<div class="jumbotron" align="block">';
echo $row['first_name'];
echo $row['last_name'];
echo $row['country'];
echo $row['username'];
echo'</div>';
echo'</div>';
}
Try by using this
<?php
$userid = (isset($_GET['id']) ? $_GET['id'] : NULL);
if ($userid) {
$userinfo = $DB->query_first("SELECT * FROM `users` WHERE `id` = '$userid'");
print_r($userinfo);
?>
<table>
<tr>
<td>First Name</td>
<td><?=$userinfo['first_name']?></td>
</tr>
<tr>
<td>Last Name</td>
<td><?=$userinfo['last_name']?></td>
</tr>
............
............
</table>
<?php } ?>
do not use null use a empty string "" that is what you want sql well do nothing with an empty string it is just white space, enough about sql injection attacks wtf ever topic i enter.
actually make it equal to wither where userid='$userid' or "".
there is only one row so the while statement is redundant just row = mysql_fetch_array.
You can try something like this:
<?php
$userid = (isset($_GET['id']) ? $_GET['id'] : NULL);
if ($userid) {
$userinfo = $DB->query_first("SELECT * FROM `users` WHERE `id` = '$userid'");
print_r($userinfo);
echo'
<div class="container">
<div class="jumbotron" align="block">
'.$userinfo['first_name'].' <br>
'.$userinfo['last_name'].' <br>
'.$userinfo['country'].' <br>
'.$userinfo['username'].' <br>
</div>
</div>';
?>

Categories