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.
Related
Hi I have added a function to my website where the user can cancel a booked ticket using the code: cancel.php
<?php
session_start();
include('config.php');
mysqli_query($con,"delete from tbl_bookings where book_id='".$_GET['id']."'");
$_SESSION['success']="Booking Cancelled Successfully";
header('location:profile.php');
?>
and I tried to add a function to the same ticket that the user can cancel to print ticket, so the user can print this ticket, the code i used is: print.php
<?php
session_start();
include('config.php');
window.print(mysqli_query($con,"select from tbl_bookings where book_id='".$_GET['id']."'"));
header('location:profile.php');
?>
the link to these two classes in a class called profile.php, and this bit is in the line where it says:
Cancel /Print Ticket
I would be happy if you can tell me how to print this data.. thanks
the use of $bkg
$bk=mysqli_query($con,"select * from tbl_bookings where user_id='".$_SESSION['user']."'");
if(mysqli_num_rows($bk))
{
?>
<table class="table table-bordered">
<thead>
<th>Booking Id</th>
<th>Movie</th>
<th>Theatre</th>
<th>Screen</th>
<th>Show</th>
<th>Seats</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
<?php
while($bkg=mysqli_fetch_array($bk))
{
$m=mysqli_query($con,"select * from tbl_movie where movie_id=(select movie_id from tbl_shows where s_id='".$bkg['show_id']."')");
$mov=mysqli_fetch_array($m);
$s=mysqli_query($con,"select * from tbl_screens where screen_id='".$bkg['screen_id']."'");
$srn=mysqli_fetch_array($s);
$tt=mysqli_query($con,"select * from tbl_theatre where id='".$bkg['t_id']."'");
$thr=mysqli_fetch_array($tt);
$st=mysqli_query($con,"select * from tbl_show_time where st_id=(select st_id from tbl_shows where s_id='".$bkg['show_id']."')");
$stm=mysqli_fetch_array($st);
?>
<tr>
<td>
<?php echo $bkg['ticket_id'];?>
</td>
<td>
<?php echo $mov['movie_name'];?>
</td>
<td>
<?php echo $thr['name'];?>
</td>
<td>
<?php echo $srn['screen_name'];?>
</td>
<td>
<?php echo $stm['start_time'];?>
<?php echo $stm['name'];?>
</td>
<td>
<?php echo $bkg['no_seats'];?>
</td>
<td>
£ <?php echo $bkg['amount'];?>
</td>
<td>
<?php if($bkg['ticket_date']<date('Y-m-d'))
{
?>
<i class="glyphicon glyphicon-ok"></i>
<?php
}
else
{?>
Cancel /Print Ticket
<?php
}
?>
</td>
</tr>
<?php
}
?></tbody>
enter image description here
You can't call window.print() within PHP code since it's a javascript function
header('location:profile.php'); will redirect the page before the javascript have the chance to execute the code. Replace that code with a javascript code which executes after you print the page.
Your print.php:
<?php
session_start();
include('config.php');
$result = mysqli_query($con, "select * from tbl_bookings where book_id='{$_GET['id']}'"); // You should replace this with prepare statement
$row = $result->fetch_array();
// assume that your booking table has columns: id, movie_name, time
echo "<table>
<tr><td>Booking ID</td><td>{$row['id']}</td></tr>
<tr><td>Movie Name</td><td>{$row['movie_name']}</td></tr>
<tr><td>Time</td><td>{$row['time']}</td></tr>
</table>";
?>
<script>
window.print();
window.location.href = "profile.php"
</script>
Stop coding now!
You need to learn the very basic of how PHP + MySQL + HTML + JS work together.
At the moment, you don't need to know what's wrong with your code. You need to learn some basic tutorials, then re-write your code from scratch. Many tutorials all over the intermet. Read this.
Extra Explanation
Server = where your code lives.
Client = the browser.
PHP & MySQL live in the server ONLY, work on the server, handled by the server.
HTML + CSS + JS prepared by the server, server then send it to client, then handled by client (the browser). So they start working when in the client (the browser). As long as they're on the server, they are just strings.
So it's always like:
Browser request file from server (http://www.mywebsite.com/something.php). This is known as the request.
Server runs the php file (something.php), which may generate output (HTML+CSS+JS), server then send the output to the client (browser). This is known as response.
Client (browser) then receives the output (as plain strings), then browser runs the code (JS).
Conclusion:
Don't tell server to run JS, don't tell client (browser) to run PHP or MYSQL.
I've modified your code to work and to much more secured way using prepare statement.
<table>
<tr><th> id </th> <th> time </th> </tr>
<?php
if (!$bk = $con->prepare("select * from tbl_bookings where user_id = ? ")) {
echo $con->error; // show error message when SQL query is wrong or goes kaboom!
} else{
$bk->bind_param("s",$_SESSION['user']); //bind the blind parameters, "s" stands for string
$bk->execute ();// execute the query
$bk_result = $bk->get_result(); // get results
}
while ($bk_row = $bk_result->fetch_assoc()){ ?>
<tr><td> <?php echo $bk_row['id']; ?> </td> <td> <?php echo $bk_row['id'] ?> </td> </tr>
<?php } //end while loop ?>
</table>
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.
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> Edit </td>';
echo '<td> Delete </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
?>
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.
This question already has answers here:
Deleting entry from MySQL table using PHP variable
(2 answers)
Closed 9 years ago.
I know this question has been asked too many times but I've searched and found nothing to solve my problem. In the table I have 4 columns: id (auto increment and primary key), type, quantity and date. The problem is when I press delete link it won't delete specific row I want and please forget about code injection, this is meant to be a sample program. Thanks.
The code for a table is like this:
<div id="content" align="center">
<table border="1">
<tr>
<td>Item</td>
<td>Quantity</td>
<td>Date</td>
<td></td>
</tr>
<?php
include("connect.php");
$query=("SELECT * FROM purchase");
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['1'];?></td>
<td><?php echo $row['2'];?></td>
<td><?php echo $row['3'];?></td>
<td>Delete</td>
</tr>
<?php
}
?>
</table>
</div>
And the delete function:
<?php
include("connect.php");
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="purchase";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
$query=("SELECT * FROM purchase");
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$id=$row[0];
mysql_query("DELETE from purchase WHERE id='$id'");
header("location:purchasehistoryadmin.php");
?>
when user clicks "Delete" then delete.php is called, so purchase id which want to be deleted should be transfer via delete.php,
as you about "Injection", below code is just example. moreover, CSRF is more dangerous, to preventing SQL Injection is easy, but CRSF is little bit difficult.
list.php
<td>Delete</td>
delete.php
$id = $_GET['id'];
mysql_query("DELETE from purchase WHERE id='$id'");
You visited delet.php but you didnt say which id you want to delete. You have to build url like
delete.php?param=5
use $_GET to catch id and pass it to query.( Now you are deleting just first row)
Also check this http://www.w3schools.com/php/php_forms.asp
Or
http://php.net/manual/en/reserved.variables.get.php