I am trying to create a table that will allow me to delete a row by clicking a delete button. I did find an article on here at the following link that did provide some help but I am still unable to get it to work: Show all rows in mysql table then give option to delete specific ones .I have written most of the code but I am having problem with line 10 on the delete.php page. Ideas?
Main.php
$result = mysqli_query($con,"SELECT * FROM cs_general_info");
echo "<table><tr><td>Delete</td><td>First Name</td><td>Last Name</td><td>Address</td>td>Phone</td><td>E-Mail Address</td></tr>";
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td>
<form action="delete.php" method="POST">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
<input type="Submit" value="Delete"></form>
</td>
<?php
echo "<td>" . $row['id'] ."</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
Delete.php
"DELETE FROM cs_general_info WHERE id=".mysql_real_escape_string($delete_id);
Hopefully delete.php is more than that single line. In delete.php you will want to catch the POST method and the $row[id]; bind it, then delete it.
To get the id of the row you want to delete in your delete.php file, you need to get the variable, like this:
$delete_id = $_POST['delete'];
WARNING: This is the very basic functionality you need to get this to work. However, you will need to implement many other levels of security before this should ever go into any production code.
If that is your delete.php, then you are missing a lot. You need a database connection and you need to execute the SQL command against the database. But that is the least of your worries until you get your parameters via $_POST.
Here is the PDO Manual for the database connection and SQL execution.
And here is the manual for $_POST.
You want to either put a link or inline form within each of your table’s rows, and then have a script that deletes the specified row and returns the user to your page.
<table>
<tbody>
<?php foreach ($results as $result): ?>
<tr>
<td><?php echo $result->title; ?></td>
<td>
<form action="delete.php" method="post">
<input type="hidden" name="id" value="<?php echo $result->id; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And then delete.php:
<?php
if (isset($_POST['id']) && intval($_POST['id']) > 0) {
// create PDO instance; assign it to $db variable
$sql = "DELETE FROM `table` WHERE `id` = :id LIMIT 1";
$smt = $db->prepare($sql);
$smt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$smt->execute();
}
header('Location: index.php');
Related
Here is my code. There's is a "Edit" link. I want to update data and save with that link
$op_sql = "SELECT * FROM tbl_users";
$result = $con->query($op_sql);
if ($result->rowCount() > 0)
{
echo "<table class='table' style='margin-left: 301px; margin-top: 10px; background-color: white;'>-;
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Email</th>";
echo "<th>Date of Birth<th>";
echo "<th></th>"; echo "</tr>";
while($row = $result->fetch())
{
echo "<tr>";
echo "<td>" . $rowrID1 . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Email']. "</td>";
echo "<td>" . $row['Date of Birth'] . "</td>";
echo "<td><a href='?id=".$row['ID']."'>Edit</a></td>";
echo "</tr>";
}
echo "</table>"; unset($result);
You can add the user_edit.php url in anchor tag href to edit the user details like this.
echo "<td><a href='user_edit.php?id=".$row['ID']."'>Edit</a></td>";
user_edit.php
Here you can get the id of specific user and get the details from database and create update form like this.
if(isset($_GET['id']) && $_GET['id']!='')
{
$op_sql = "SELECT * FROM tbl_users where id=$_GET['id']";
$result = $con->query($op_sql);
if ($result->rowCount() > 0)
{
$row = $result->fetch();
?>
<form action="user_update.php" method="post">
<input type="text" name="Name" value="<?php $row['Name'] ?>" />
.
.
<input type="hidden" name="id" value="$_GET['id']" />
.
.
<input type="submit" name="update" value="update" />
<?php
}
}
user_update.php
Here you can get the updated form data and update in database
if(isset($_POST['update']) && isset($_POST['id']) && $_POST['id']!='' )
{
// here you can get the updated form data and update in database
// update user set Name=$_POST['Name'],.... where id=$_POST['id'];
}
NOTE :
Try to use Prepared statement or PDO
I am giving an answer from This question you can use the same answer in your context here I'm providing the code from the accepted answer.
You can use a get method here in place of the post according to your situation.
HTML form:
<form method="post" action="handler.php">
<button type="submit" name="passed" id="passed" class="btn btn-success btn-flat"><i class="fa fa-check"></i></button>
<button type="submit" name="insufficient" id="insufficient" class="btn btn-danger btn-flat"><i class="fa fa-times"></i></button>
</form>
PHP:
<?php
// db connection
if(isset($_POST['passed'])){
$allowed = mysqli_query($conn," UPDATE users SET Access = "1" WHERE id = '27' ");
}
if(isset($_POST['insufficient'])){
$notallowed = mysqli_query($conn," UPDATE users SET Access = "0" WHERE id = '453' ");
}
Be careful if this has any user interaction at any given point.
Use a prepared statement, or PDO with prepared statements, they're much safer.
Thanks in advance for any light shed.
I have a mysql database consisting of customers with some fields pertaining to each customer. currently running on one of my lamp servers. There is security risks with my code at the moment, but I plan to get the functionality i'm looking for and then reconfigure the code for a tighter security. At the moment I have an html index file that calls on php script to search mysql database by firstname or lastname. Upon this query it displays a list of users and allows me to modify the user. When I click modify it pulls the correct customer id number, but it is not displaying any current information, nor allowing me to update the info.
To summarize, I would like to search a customer, and it pull up selected fields and show the content and allow me to actively change the data and resend it to the database.
My search.html code:
<html>
<body>
<form action="scripts/search.php" method="post">
Firstname: <input type="text" name="firstname">
<input type="submit">
</form>
<form action="scripts/lastnamesearch.php" method="post">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>
<form action="scripts/phonenumbersearch.php" method="post">
Phone Number: <input type="text" name="phone">
<input type="submit">
</form>
</body>
</html>
MY search.PHP Script:
//this script allows me to search the database by filling out one of the forms and clicking submit. Each of the forms calls upon it's own individual script, I realize that this is probably cumbersome, due to my lack of coding knowledge.
<?php
$con=mysqli_connect("localhost","root","*****","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customers WHERE `firstname` LIKE '$_POST[firstname]'");
echo "<table border='1'>
<tr>
<th>id</th>
<th>firstname</th>
<th>lastname</th>
<th>phone</th>
<th>address</th>
<th>notes</th>
<th>additional notes</th>
<th>passwords</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['notes'] . "</td>";
echo "<td>" . $row['addnotes'] . "</td>";
echo "<td>" . $row['passwords'] . "</td>";
echo "Modify User";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
My modify.php script:
//this is where I believe one of my problems lie. when I click modify user on the search.php script it calls on this script and it loads the correct user/customer id in the address bar, but it doesn't show any existing data, nor does it update the data that I fill in the cells.
<?php
$con=mysqli_connect("localhost","root","crapola1","Computition");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$mysqli_query = "SELECT * FROM customers WHERE ID = $_get[id]";
$mysqli_result = mysqli_query($mysqli_query);
$customer = mysqli_fetch_array($mysqli_result);
?>
<h1> You are modifying a user</h1>
<form action="<?php echo $SERVER['PHP_SELF']; ?>" method="post">
Firstname<input type="text" name="inputFirstname" value="<?php echo $row['firstname']; ?>" /><br />
Notes<input type="text" name="inputNotes" value="<?php echo $row['notes']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify" />
</form>
Thanks again,
I've been searching on this topic for about a week now and have pieced together this much, but can't seem to get over this "hump"
$_GET is a super global array . It should be in UPPERCASE.
Change the query on your modify.php here
SELECT * FROM customers WHERE ID = $_get[id] to upper case.
Must be..
SELECT * FROM customers WHERE ID = ".$_GET['id']
Also, It is strictly not advised to pass the $_GET or $_POST parameters directly to your query as it leads to SQL injection. You need to switch over to PreparedStatements
I'm having an issue trying to update multiple entries in my database via a php populated drop down menu. Here is the code on my page that populates the table showing me all entries currently in my database:
$result = mysqli_query($con,"SELECT * FROM Submissions");
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Title</th>
<th>Text</th>
<th>Public Post OK?</th>
<th>Date/Time Submitted</th>
<th>Approved?</th>
<th>Test Approved</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . nl2br($row['text']) . "</td>";
echo "<td>" . $row['publicpost'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "<td><select name=\"approved\"><option value=\"" . $row['approved'] . "\">" . $row['approved'] . "</option><option value=\"yes\">Yes</option><option value=\"no\">No Again</option></select></td>";
echo "<td>" . $row['approved'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<br><br>
<form action="update.php" method="post">
<input type="submit" name="SubmitButton" value="Update" class="submit" style="cursor:pointer;">
</form>
<?php
mysqli_close($con);
?>
This is the php code for "update.php":
$approved = $_POST['approved'];
mysqli_query($con,"UPDATE Submissions SET approved = $approved");
$update_query= "UPDATE Submissions SET approved = '$approved'";
if(mysqli_query($con,$update_query)){
echo "updated";}
else {
echo "fail";}
?>
<form action="approvesubmissions.php">
<input type="submit" value="Approve Submissions page">
</form>
The goal is to have the ability to update the field "approved" with a drop down menu from "NO" to "YES" or vice versa. Instead, what is happening with this query, is that it is erasing the data in the "approved" field instead of updating it. I'm somewhat new to php and i have researched a TON on this and have come up with no solutions. Any help is GREATLY appreciated!
First, let's assume 'approved' is a TINYINT(1) or something.
Your select html should be more like this. It will autofill based on the DB value.
$selected = 'selected="selected"'; // pre-selection attribute
$isApproved = !!$row['approved']; // is this active? (approved is 1 or 0)
echo '<select name="approved">
<option value="1" ' . ($isApproved ? $selected : '') . '>Yes</option>
<option value="0" ' . (!$isApproved ? $selected : ''). '>No</option>
</select>';
Secondly, your form is at the bottom of the table, but your input that you want is in the table. When you submit your form, there is no $_POST['approved'], because that's technically not in a form. To fix, you'll need to put your opening form tag at the top before the table. Then, you'll want to put your submit button and closing form tag at the end, after you've echoed the table out.
Thirdly, your post.php page should NOT ever take user input directly into a query. But, simply do this:
// Convert input to boolean answer, then int (for the query).
$approved = isset($_POST['approved']) ? (int)!!$_POST['approved'] : 0;
mysqli_query($con,"UPDATE Submissions SET approved = '$approved'");
While we're on the topic, this would be a great time to jump into prepared statements for your project. It might sound scary, but it can save you from SQL injection.
// Make the prepared statement
$query = mysqli_prepare("UPDATE Submissions SET approved = ?");
// Safely bind your params
mysqli_stmt_bind_param($query, "i", $approved);
// Run it
mysqli_stmt_execute($query);
// "close" the statement (hint: it's reusable for things like bulk updates, etc)
mysqli_stmt_close($query);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I simply just want a button in my table to delete the specific row but everything I search for ends up being some completely different way compared to how I have set it up.
<?php
// Connects to your Database and if it cant it dies
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// this selects the db
mysql_select_db("test", $con);
// this passes the query into the variable result
$result = mysql_query("SELECT * FROM items");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Quantity</th>
<th>Delete</th>
<tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . 'Delete' . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
//end php
?>
<html>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="Name" />
Quantity: <input type="text" name="Quantity" />
<input type='submit' name='add' value='add' />
</form>
</body>
</html>
i would like the hyperlink to delete the row is contained in.
You need to add the ID of the record you want to delete to the delete url, e.g.:
echo "<td>Delete</td>";
Then, in your delete.php script, you'd do:
<?php
$id = intval($_GET['id']);
$sql = "DELETE FROM yourtable WHERE id=$id";
$result = mysql_query(sql);
Of course, that's not a full script, but shows you the basics of what needs to be done. Be careful with using the passed-in value in your query - don't want to let an SQL injection hole ruin your day.
However, be aware that using a 'GET' type query for this sort of thing is generally a bad idea. If this page gets spidered by Google (for one), you'll find that the simple act of spidering has nuked ALL of your records.
You need to pass the ID of the row as paramter to the delete.php script
echo "<td>" . 'Delete' . "</td>";
you can use the id of the current row and send it to delete.php:
echo "<td>" . 'Delete' . "</td>";
then in delete.php get the id by $deleteId = $_GET['id'] and use it...
Try changine the URL to something like echo '<a href="delete.php?ID=' . $row['ID'] . '">'
BTW - Not a good idea to use root!
I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)