Remove MySQL row with button - php

I am really struggling here and not sure why. I am trying to remove a row in my data base when the user click the delete button thats in the same button as the row their trying to remove.
Home.php
<table class="table table-bordered table-striped table-responsive sortable">
<tr class="header">
<td>id</td>
<td>Rep</td>
<td>Date</td>
<td>Name</td>
<td>P_O</td>
<td>Due Date</td>
<td>Terms</td>
<td>Aging</td>
<td>Open Balance</td>
<td>remove</td>
</tr>
<?php
while($row = mysql_fetch_array($query)) {
$className ="";
if ($row['Aging'] >= 45)
{
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44)
{
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button id='" .$row['id']. "' value='" .$row['id']. "' class='btn btn-danger'> Delete</button></td>";
}
?>
</table>
deletepage.php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_GET['id'])){
$userID = (int) $_GET['id'];
if(!empty($_GET['id'])){
$delete = mysqli_query($conn, "DELETE FROM Book1 WHERE id='$userID'");
}
if($delete){
echo "Record deleted successfully";
}else{
echo "Sorry, record could not be deleted";
}
}
?>

If you connect with mysqli, use mysqli throughout.
I've added an i here:
$delete = mysqli_query($conn, "DELETE FROM Book1 WHERE id='$userID'");
And change your button once to this. You aren't passing the variable to get currently, you;d do that by adding a question mark to the URL and specifying variables. Also, Since you are using twitter bootstrap, anchors with class btn will look like a button, so a form is not necessary.
echo "<td><a href='deletepage.php?id=" .$row['id']. "' value='" .$row['id']. "' class='btn btn-danger'> Delete</a></td>";

Starting at while($row = mysql_fetch_array($query)) {, it looks like you start a <tr>, but it doesn't look like you ever close it. At the bottom of your <td>s, you'll want a echo "";
Not a huge deal, and this won't fix your issue.
Like I said in the comment, action isn't realyl an attribute of <button>. See here
What you will probably need to do is wrap it in a form, which you said you did, and add type="submit" to the button tags.
<form action="deletepage.php" method="GET">
...table html
echo "<td><button id='" .$row['id']. "' type="submit" value='" .$row['id']. "' class='btn btn-danger'> Delete</button></td>";
</form>
This sounds like what your issue is, to me at least. You need to submit an html form to deletepage.php, or try another route like an AJAX request to deletepage.php.

Related

How to delete a row in php?

I made from in php. When I select a class, for example I select the class9, it shows me the table of class9. I also have inserted a row in the table containing the delete button to delete the corresponding row. Now I want to delete a row buy clicking the button which is in the row. how can I do that?
First I choose a class from this option as in the image below ;The image from which we select the class
And then the corresponding table is going to be shown.
This is the image. When I click on the button, the corresponding row should be deleted.
<?php
include "connection.php";
?>
<!doctype html>
<html>
<head>
<title>KDR</title>
</head>
<body>
<table border="2px" width="50%" height="auto">
<tr>
<th>No</th>
<th>Name</th>
<th>F/Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<?php
$table = $_POST['formCountry'];
$sql = "SELECT * FROM $table";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td><form method='POST' ><input type='submit' name='deletestudent' value='Delete'/></form></td>";
echo "</tr>";
}
?>
</table>
</body>
Something like this. Maybe will need to adjust it a bit.
Your table button:
echo "<td><form method='POST' action="delete_row.php" ><input type='submit' name='deletestudent' value="'.$row['id'].'"/></form></td>";
In PHP (delete_row.php) you should do the following
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['id']) and is_numeric($_POST['id']))
{
$delete = $_POST['id']
$stmt = $conn->prepare("DELETE FROM YOURTABLENAME WHERE id = ?");
$stmt->bind_param('i', $delete);
$stmt->execute();
$stmt->close();
}
Note: Not tested and I'm using mysqli_* here.
Update: As #icecub suggested you can use also hidden field to get the ID
echo "<td>
<form method='POST' action='delete_row.php' >
<input type='hidden' name='deletestudent' value='".$row['id']."'/>
<input type='submit' value='Delete'/>
</form>
</td>";
This is how not to do , see the comments below , important !
Should be send the current id of the element , so when you click the button
get the element ID by $_GET['id'];
<td><a href='?id=".$row['id']."'>delete</a></td>
if (isset($_GET['id'])) {
//Throw query DELETE ... WHERE id = $_GET['id'];
}

php mysql UPDATE command wont update

All the data is loaded into a table, each row as a button. Once the button has been pressed, the row has to be updated. But when I click on the button, nothing happens. The text box on the rows return to its original value... It is really starting to cheese me off
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'dragondrivingschooldb'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='$_POST[txtfirstname]' WHERE BookingID='$_POST[txtid]' "); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT * FROM booking"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form action=EditStudent.php method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name=update type=submit value=update /> </td>"; //once press update row this button is apart of
echo "<td> <input type=text value=" . $row['BookingID'] . " name=txtid /> </td>";
echo "<td> <input type=text value=" . $row['FirstName'] . " name=txtfirstname /> </td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
mysqli_close($con); //Close connection
?>
</html>
I think that BookingID it is an integer, so your update line need to be:
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID=" . $_POST['txtid'] . ""); //excute UpDate Query
EDIT:
I tested your script and the problem was that you closed the form outside the while loop. Now its working
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'all_tests'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE test_1 SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID='" . $_POST['txtid'] . "'"); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT *FROM test_1"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name='btnUpdate' type='submit' value='update' /> </td>"; //once press update row this button is apart of
echo "<td> <input type='text' value=" . $row['BookingID'] . " name='txtid' /> </td>";
echo "<td> <input type='text' value=" . $row['FirstName'] . " name='txtfirstname' /> </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con); //Close connection
?>
at first check that $_POST[txtid] has value or not. and be sure that field name is correct or incorrect.
There are no input field in your html that has name btnUpdate. What I can see its name is update. Therefore your row:
if (isset($_POST['btnUpdate'])) {
would never be true

2 forms using PHP. One for adding and one for adding changes

I'm still making the orderform, I've been working on the "save changes function".
By this I mean, if people make changes to the table, they can click on a button and it will update the database (where I get my data from).
Link to the image.
"Bestelling toevoegen" is the adding form, if I fill in the form, and click on "Toevoegen" it will display a new record to the table above.
The problem is, I can't seem to save the changes (Wijzigigen opslaan) of "Status".
Here's the full code:
$con=mysqli_connect("localhost","root","","bestelformulier");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM overzicht");
echo "<form method='post'>";
echo "<table align='center' width='700px' border='2'>
<tr>
<th>Ordernr</th>
<th>Klantnaam</th>
<th>Productnaam</th>
<th>ProductID</th>
<th>Status</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$status = $row['status'];
$ordernr = $row['ordernr'];
echo "<tr>";
echo "<td>" . $row['ordernr'] . "</td>";
echo "<td width='150px'>" . $row['klantnaam'] . "</td>";
echo "<td width='200px'>" . $row['productnaam'] . "</td>";
echo "<td>" . $row['productid'] . "</td>";
echo "<td><select>
<option>" . $row['status'] . "</option>";
if($row['status'] != "Niet besteld")
echo "<option>Niet besteld</option>";
if($row['status'] != "Besteld")
echo "<option>Besteld</option>";
if($row['status'] != "Onderweg naar hoofdlocatie")
echo "<option>Onderweg naar hoofdlocatie</option>";
if($row['status'] != "Onderweg naar vestiging")
echo "<option>Onderweg naar vestiging</option>";
if($row['status'] != "Ontvangen")
echo "<option>Ontvangen</option>";
echo "</select></td>";
echo "</tr>";
}
echo "<tr>";
echo "<td></td><td></td><td></td><td></td>";
echo "<td><input type='submit' name='wijzigen' value='Wijzigingen Opslaan'/></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
if(isset($_POST['wijzigen'])) {
$query = mysqli_query("UPDATE overzicht SET status=$status WHERE ordernr=$ordernr");
}
mysqli_close($con);
//Table Toevoegen
$con=mysqli_connect("localhost","root","","bestelformulier");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<br/><br/><br/>";
echo "<h5>Bestelling Toevoegen</h5>";
echo "<form method='post'>";
echo "<table width='700px' border='1'>
<tr>
<th>klantnaam</th>
<td><input type='text' name='klantnaam'/></td>
</tr>
<tr>
<th>Productnaam</th>
<td><input type='text' name='productnaam'/></td>
</tr>
<tr>
<th>productid</th>
<td><input type='text' name='productid'/></td>
</tr>
<tr>
<th>Status</th>
<td>
<select name='status'>
<option value='Niet besteld'>Niet besteld</option>
<option value='Besteld'>Besteld</option>
<option value='Onderweg naar hoofdlocatie'>Onderweg naar hoofdlocatie</option>
<option value='Onderweg naar vestiging'>Onderweg naar vestiging</option>
<option value='Ontvangen'>Ontvangen</option>
<select>
</td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='toevoegen' value='Toevoegen'/></td>
</tr>";
echo "</table>";
$klantnaam = $_POST['klantnaam'];
$productnaam = $_POST['productnaam'];
$productid = $_POST['productid'];
$status= $_POST['status'];
if(isset($_POST['toevoegen'])) {
$query = mysqli_query($con,"INSERT INTO overzicht (klantnaam, productnaam, productid, status)
VALUES ('$klantnaam', '$productnaam', '$productid', '$status')");
$current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header ('Location: ' . $current_url);
exit ();
}
echo "</form>";
mysqli_close($con);
Hope I made it all clear for you, if not I will reply as soon as possible.
Thanks in advance!
You are not reading the status from the $_POST variable.
You are reading $status from the database:
$status = $row['status'];
and then you are setting it again
$query = mysqli_query("UPDATE overzicht SET status=$status WHERE ordernr=$ordernr");
So you set it to the same value as it already is.
Add a $status = $_POST['status']; before the query. Also, you are not reading $ordernr from $_POST, so you are always setting the status to the last item read from your database.
You are also missing single quotes in the query, it should be status='$status'. Last, but not least, take a look at prepared statements. Right now your code is vulnarable to SQL injections.
Edit:
You have to rethink the form of your list. Your select elements don't have a name, so it can't be transmitted to the server at all. Also, you have to provide the ID of the order number for each order ... either you make a form for each order (I'd recommend that), or you use arrays for your form element names (for example: <select name="status[$ordernr]">, simplified).
Why in the universe you have assigned $status = $row['status']; and not using $status in your while Loop.
Second you are using single quotes around variables in the insert query, you don't have to do this, else mysqli will take them as string instead of variables, put the variables in double quotes and query in single.
If this doesn't help, try printing the post data. Also you haven't given name to your forms. Please give forms some name and to your form elements as well.
This may help.

Delete Row with Input Button

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');

Deleting multiple rows from mysql with checkbox?

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 ;)

Categories