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
Related
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.
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>
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 mysql database named "drinks", in that database I have one table named "persons" and in "persons" I have two people, Bryan(fname) Fajardo(lname) 21(age) and Andross H Age:20.
In my index.php I have links set up from all of the people in table persons.
I am trying to get my links to work so that when I click on either name, the information relevant from that person is outputted into my other page (where the link goes to) which is: insert.php.
I have been trying for hours to run some test by clicking on the Bryan link and outputting only his last name etc. etc. My objective: is to be able to link the people from "persons" table and then upon click go to insert.php and output that person's information there.
Here is my current code from Index.php.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
//Connect to the database
$con = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">MSQL Connected.</span>' ;
}
$result = mysqli_query($con,"SELECT * FROM persons");
while($row = mysqli_fetch_array($result)) {
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
}
mysql_close();
?>
</body>
</html>
and here is my Insert .php where I want the relevant information to be printed.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class = "full-header">
<div class = "mid-header span12 center">
</div>
</div>
<div class = "main-content-container full_w">
<div class = "span12 main-content center">
<?php
$cont = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">yay</span>' ;
}
$fname = $_GET['fname'];
$sel = ($cont,"SELECT * FROM persons WHERE fname ='%$fname%'");
while($rower = mysqli_fetch_array($sel)) {
Print $rower['lname'];
//why is this not printing Bryan's last name?
}
?>
</div>
</div>
</body>
</html>
Thank you in advance, I appreciate the help, I have just recently gotten into php and database building/summoning.
EDIT: I also have been reading that this is becoming deprecated and PDO is going to be used now, if you have a solution that involves PDO, I would appreciate that as well, but I am very new to PDO.
EDIT 2: Changed "table" to "persons" in insert.php query.Still did not fix.
I can understand how it is when first starting out. Once you wrap your mind around the basic parts of it the rest will flow.
Since you asked for a better way I am going to suggest a class I personally use in all my projects.
https://github.com/joshcam/PHP-MySQLi-Database-Class
Of course don't forget to download the simple MYSQLI class from the link above and include it just like I do below in your project. Otherwise none of this will work.
Here us the first page which contains the table with all the users from your persons Db table. We list them in a table with a simple edit/view button.
PAGE 1
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all users in the DB table persons
$users = $db->get('persons'); //contains an Array of all users
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th> </th>
<?php
//loops through each user in the persons DB table
//the id in the third <td> assumes you use id as the primary field of this DB table persons
foreach ($users as $user){ ?>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<a href="insert.php?id=<?php echo $user['id']; ?>"/>Edit/View</a>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
So that ends your first page. Now you need to include this code on your second page which we are assuming is called insert.php.
PAGE 2
<!--add this to your insert page-->
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all the user where the GET
//variable equals their ID in the persons table
//(the GET is the ?id=xxxx in the url link clicked)
$db->where ("id", $_GET['id']);
$user = $db->getOne('persons'); //contains an Array of the user
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>user ID</th>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<?php echo $user['id']; ?>
</td>
</tr>
</body>
</html>
You have two main errors. On index.php you are wrapping your query string values in quotes
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
This should really be
Print '<dd><a href="insert.php?
fname='.$row['fname'].'">'.$row['fname'].'</a></dd>';
Next, on your second page, you need to use LIKE on your query.
$sel = ($cont,"SELECT * FROM persons WHERE fname LIKE '%$fname%'");
That said, you really should use parameters because the current method is going to open your script up to SQL Injection, and you should consider using a primary key in your querystring instead of passing the person's name.
Print '<dd><a href="insert.php?
id='.$row['id'].'">'.$row['fname'].'</a></dd>';
And your query
$id = intval($_GET['id']);
$sel = ($cont,"SELECT * FROM persons WHERE id = $id");
One final note, on your index page, you are using mysql_close instead of mysqli_close to close your database connection.
I have a table with the following fields:
email - name - username - userid
currently the data in this table is pulled into a html table.
In a seperate table i have all the user's data / information.
What i would like to do is click on a name from the first table (consisting of email - name - username)
And have that users information shown on its own like a report generation.
Both the tables have the same unique userid's applied so could someone enlighten me as to the best way to do this?
Thanks.
Surround the name with an anchor tag that has the id as some parameter.
I'd do it with 2 templates where one lists all the users (userList.php) and the other one shows detailed information about a user (userInformation.php).
userList.php:
<table>
<tr>
<th>
<a href="userInformation.php?id=<?php echo $user->id;?>">
<?php echo $user->username;?>
</a>
</th>
<td><?php echo $user->email;?></td>
<td><?php echo $user->propN;?></td>
</tr>
...
...
</table>
userInformation.php:
<?php
$userId = $_POST['id'];
$user = someFunctionForGettingTheUserPerhaps($userId);
?>
<table>
<tr>
<th><?php echo $user->username;?></th>
<td><?php echo $user->email;?></td>
<td><?php echo $user->password;?></td>
<td><?php echo $user->name;?></td>
<td><?php echo $user->propN;?></td>
...
...
</tr>
</table>
EDIT: Replaced '.' with '->' since the latter is the property accessor notation in PHP.
Set the onclick attribute of each table row to
echo('<tr onclick="location.href=\'userdet.php?id='.$row['userid'].'\'">
Where userdet.php is a page that puts the information you want into a HTML table.
edit
You could also try putting the data in like this http://www.jsfiddle.net/dduncan/UuA9E/
although that could get slow if you have a massive users table. (click the table row)