Delete SQL data from database with php page - php

I am making an application to secure doors and windows in your house. The app is done for 80% but i can't figure out how I can delete a database record of a door of house. The problem is I can't find a way to read out the right data to delete the record. Could you please look in my scripts i made for the delete page?
I have one page to insert al the data in a table to overview all the devices that are "connected" to the app.
<section>
<form action="verwijderen.php" method="post">
<?php
$sql = "SELECT device_id, naam, plaats.plaats, type.type, status FROM devices, type, plaats, status
WHERE devices.type_id = type.type_id
AND plaats.plaats_id = devices.plaats_id
AND status.status_id = devices.status_id";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
echo '<table><tr><td>ID</td><td>Naam</td><td>Plaats</td><td>Type</td><td>Status</td><td>Verwijderen</td></tr>';
while($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>' .$row['device_id']. '</td>';
echo '<td>' .$row['naam']. '</td>';
echo '<td>' .$row['plaats']. '</td>';
echo '<td>' .$row['type']. '</td>';
echo '<td>' .$row['status']. '</td>';
echo '<td>';
?>
<input type="submit" value="Verwijderen" name="submit">
</form>
<?php '</td>';
}
echo '</table>';
}
?>
</section>
The other page I have is the page to delete the records that are inserted into the table. The problem with the deleting is I can't find a way to delete the records. Adding the records to the database in html with a $_POST/$_GET works fine..
<?php
error_reporting(E_ERROR);
include '../dbconnect.php';
//$connection = mysql_connect("", "", ""); // Establishing Connection with Server
//$db = mysql_select_db("cerar", $connection); // Selecting Database from Server
if(isset($_POST['submit']))
{ // Fetching variables of the form which travels in URL
}
mysqli_close($con); // Closing Connection with Server
//header( "refresh:3;url=index.php" );
?>

Create a form for each row of your table, and include a hidden input field containing the key value to pass to the server. So move the opening form tag just before the input type="submit" you have, and include another hidden input, like this:
<form action="verwijderen.php" method="post">
<input type="hidden" value="<?=$row['device_id']?>" name="device_id">
<input type="submit" value="Verwijderen" name="submit">
</form>
Then in PHP you can find the device id that must be deleted in $_POST['device_id']. It should be easy to write the delete statement.

<section>
<form action="verwijderen.php" method="post">
<?php
$sql = "SELECT device_id, naam, plaats.plaats, type.type, status FROM devices, type, plaats, status WHERE devices.type_id = type.type_id AND plaats.plaats_id = devices.plaats_id AND status.status_id = devices.status_id";
$result = $con->query($sql);
if ($result->num_rows > 0) {
echo '<table>
<thead>
<tr>
<th>ID</th>
<th>Naam</th>
<th>Plaats</th>
<th>Type</th>
<th>Status</th>
<th>Verwijderen</th>
</tr>
</thead>
<tbody>';
while($row = $result->fetch_assoc()){
echo '<tr>';
echo '<td>' .$row['device_id']. '</td>';
echo '<td>' .$row['naam']. '</td>';
echo '<td>' .$row['plaats']. '</td>';
echo '<td>' .$row['type']. '</td>';
echo '<td>' .$row['status']. '</td>';
echo '<td>';?>
<input type="hidden" value="<?php echo $row['device_id']; ?>" name="device_id">
<input type="submit" value="Verwijderen" name="submit">
<?php '</td>';
}
echo '</tbody>
</table>';
}
?>
</form>
</section>
PHP Code
<?php
error_reporting(E_ERROR);
include '../dbconnect.php';
extract($_POST);
//$connection = mysql_connect("", "", ""); // Establishing Connection with Server
//$db = mysql_select_db("cerar", $connection); // Selecting Database from Server
if(isset($_POST['submit']) && $_POST['submit'] == 'Verwijderen')
{
//delete query
//DELETE FROM devices WHERE device_id = $device_id
}
mysqli_close($con); // Closing Connection with Server
//header( "refresh:3;url=index.php" );
?>

Related

Why is only one table row updated?

I'm trying to update the rank column in the users table in MySQL using PHP, but when I try to change the values and press the update button, only the last one of the table rows is actually being updated. Here is an image of what the PHP table looks like on the webpage:
Here is the code:
<?php
include '../db/connect.php';
$con = $MySQLi_CON;
if (!$con){
die("Can not connect: " . mysql_error());
}
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE users SET rank='$_POST[rank]' WHERE user_id='$_POST[hidden]'";
$con->query($UpdateQuery);
}
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
echo "<table border=1>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Rank</th>
</tr>";
echo "<form action='test3.php' method='post'";
while($record = $result->fetch_array()){
echo '<tr>';
echo '<td>' . $record['user_id'] . '</td>';
echo '<td>' . $record['username'] . '</td>';
echo '<td>' . $record['email'] . '</td>';
echo '<td>' . '<input type="number" name="rank' . [$record['user_id']] . '" />';
echo '<td>' . '<input type="hidden" name="hidden" value="' . $record['user_id'] . '"</td>';
echo '<td>' . '<input type="submit" name="update" value="update"' . '</td></tr>';
}
echo "</table>";
for($_POST['rank'] as $user_id=>$rank){
$UpdateQuery = "UPDATE users SET rank='$rank' WHERE user_id='$user_id'";
$con->query($UpdateQuery);
}
$con->close();
The problem is all rank of each row is using the same name rank and also the hidden, the browser will override all rank and hidden value with the latest element.
change <input type="number" name="rank" /> to <input type="number" name="rank[$record['user_id']]" />
receive in php with $_POST['rank'] in array format and loop each rank.
for($_POST['rank'] as $user_id=>$rank){
$UpdateQuery = "UPDATE users SET rank='$rank' WHERE user_id='$user_id'";
$con->query($UpdateQuery);
}

Updating a mysqli table with a php form

I am trying to update the rank column in the users table in my database by presenting data in a PHP form and using a button to submit. However once i edit the data in my PHP form and press submit, the data in the database remains unchanged. I'm adding a (link to the) picture of the webpage, and the code is posted below.
Webpage image
<!DOCTYPE HTML>
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
Displays all data from 'users' table
*/
// connect to the database
include('../db/connect.php');
// get results from database
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Username</th> <th>Email</th> <th>Rank</th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = $result->fetch_array()) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['user_id'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td><input type="hidden" name="user_id[]" id="newrank" width="20px" min="0" max="100" value="' . $row['user_id'] . '"></td>';
echo '<td><form method="POST" action=""><input type="number" name="newrank[]" id="newrank" width="20px" min="0" max="100" value="' . $row['rank'] . '"></form></td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
if(isset($_POST['btn-update'])) {
for($i = 0; count($_POST["user_id"]); $i++) {
$_POST['newrank'][$i] = $MySQLi_CON->real_escape_string($_POST['newrank'][$i]); # If this function exists either, if not comment or remove this line!
$_POST['user_id'][$i] = $MySQLi_CON->real_escape_string($_POST['user_id'][$i]); # If this function exists either, if not comment or remove this line!
$MySQLi_CON->query('UPDATE users SET rank=' . $_POST['newrank'][$i] . ' WHERE user_id=' . $row['user_id'][$i] . '');
}
echo "Updated the rows.";
}
?>
<br>
<button type="submit" class="btn btn-default" name="btn-update" id="btn-update">Update</button></a>
<p>Add a new record</p>
</body>
</html>
Seems there is an error in your query statement
Modify this : if ($$MySQLi_CON->query($sql) === TRUE) {
with if ($MySQLi_CON->query($sql) === TRUE) {
You need to parse the id you wish to modify to the $_POST. Also, you need to use <form action="" method="POST"> in your code.
Didn't tested it, but the following should work:
<!DOCTYPE HTML>
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border='1' cellpadding='10'>
<thead> <th>ID</th> <th>Username</th> <th>Email</th> <th>Rank</th> <th colspan="3"></th></thead>
<tbody>
<?php
//Displays all data from 'users' table
// connect to the database
include('../db/connect.php');
// get results from database
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
// loop through results of database query, displaying them in the table
while($row = $result->fetch_assoc()) {
// echo out the contents of each row into a table
?>
<form action="" method="POST">
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['email'];?></td>
<td><input type="number" name="newrank" id="newrank" value="<?php echo $row['rank']; ?>"></td>
<td><input type="hidden" name="id" value="<?php echo $row['user_id']; ?>"><button type="submit" class="btn btn-default" name="btn-update" id="btn-update">Update</button></td>
<td>Delete</td>
</tr>
</form>
<?php
}
?>
</tbody>
</table>
<?php
if(isset($_POST['btn-update']))
{
$sql = 'UPDATE users SET rank=' . $_POST['newrank'] . ' WHERE user_id=' . $_GET['id'] . '';
if ($MySQLi_CON->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $MySQLi_CON->error;
}
}
?>
<p>Add a new record</p>
</body>
</html>

Update retrieved data

Hi there im in the process of making a page to approve and deny names in a database, I currently have it so it finds an pulls the pending requests im looking for now i wanna know how to update the row once i click approve or deny.
the values it needs to update is the NameState column to either ("approved") or ("REJECTED")
there can be any where from 1 to 100 names at a time.
Thanks Ryan
$DB_HOST = "IP";
$DB_USER = "user";
$DB_PASS = "Pass";
$DB_DTBS = "DB";
mysql_connect($DB_HOST, $DB_USER, $DB_PASS) or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db($DB_DTBS) or die(mysql_error()); // Select registration database.
$search = mysql_query('SELECT * FROM TABLE WHERE `NameState` = \'(\"PENDING")\'') or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Current Name</th>
<th>Requested Name</th>
<th>Approve or Deny</th>
</tr>";
while($row = mysql_fetch_array($search)) {
echo "<tr>";
echo "<td>" . $row['object_id'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['WishName'] . "</td>";
echo '<td> <form method="post" action=<?php echo Approve:<input type="radio" value="Approve" name="name"> Deny:<input type="radio" value="Deny" name="name"><br /> </td>';
echo "</tr>";
}
echo "</table>";
echo '<input type="Submit" value="Submit" name="Submit"> </form>';
} else {
echo("No Names to Approve");
}
?>

Use Delete Button to Delete Record from Database

I have a database containing books. On a page, I have loop that prints each record in the database which each book's title, author, publisher, date, and rating. I want to use a delete button at the bottom of each record in order to delete it.
When I click on the delete button, the page is updated, but the record is not deleted.
I have tried to find solutions to this problem, but have yet to. I tried to use the book_id category in my database table as my index, in order to identify each record and delete it but it does not work.
Here is the code for my button form, as it appears with html code:
while ($row = mysqli_fetch_array($result))
{
echo '<div id="forminput">';
$timestamp = strtotime($row['date']);
echo '<div id = "bookpicture">';
echo '<img src="images/Book Cover 8crop.jpg" alt="Book Cover">';
echo '</div>';
echo '<div id = "bookinfo">';
echo '<div id = "titleauthor">';
echo '<h3>' . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . '</h3>';
echo '<p>' . htmlspecialchars($row['author'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '</div>';
$id = htmlspecialchars($row['book_id'], ENT_QUOTES, 'UTF-8');
echo '</div>' ;
echo '<div id = "publisher">' ;
echo '<p>' . 'Published on' . " " . htmlspecialchars(date('F j, Y,', $timestamp),
ENT_QUOTES, 'UTF-8') .
" " . 'by' . " " . htmlspecialchars($row['publisher'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '<div id = "formDelete">';
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="submit" value="Update" name="myAdd" id="myAdd" style = "width:
100px" required>';
echo '<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:
100px" required>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '<hr>' ;
echo '</div>';
}
?>
Here is the code from my index.php file.
else if (isset($_POST['myDelete']))
{
$ids = mysqli_real_escape_string($link, $_POST['$id']);
$sql="DELETE FROM readbooks WHERE book_id = '$ids'";
if (!mysqli_query($link, $sql))
{
$error = 'Error with submission: ' . mysqli_error($link);
include 'php/error.html.php';
exit();
}
}
Here is the updated code.
The Problem is you are not trying to send the row ID from the form.
In Form try sending row id from the form
echo '<input type="hidden" name="id" value="$id">'
try receiving that parameter
$id = $_POST['id'];
$con = mysql_connect("host address","mysql_user","mysql_pwd");
$query = "DELETE FROM readbooks WHERE id = $id";
mysql_query($query,$con);
Moving from comment, you're not actually getting the $id anywhere. Add a field to your form:
<input type='hidden' name='id' value='$id'>
and then refer to it in your php:
$ids = mysqli_real_escape_string($link, $_POST['id']);
Since your using mysqli now, use prepared statements. Do not directly use your user input to the query! Example:
$books = array();
// connection
$con = new mysqli('localhost', 'your_username', 'password_of_username', 'your_database');
if(isset($_POST['myDelete'])) {
$book_id = $_POST['myDelete']; // get the variable id
$stmt = $con->prepare('DELETE FROM readbooks WHERE book_id = ?');
$stmt->bind_param('i', $book_id);
$stmt->execute();
}
$result = mysqli_query($con, 'SELECT * FROM readbooks');
while($row = $result->fetch_assoc()) {
$books[] = $row;
}
?>
<form method="POST">
<table border="1" cellpadding="10">
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th></th>
</tr>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['title']; ?></td>
<td><?php echo $book['author']; ?></td>
<td><?php echo $book['publisher']; ?></td>
<td><button type="submit" name="myDelete" value="<?php echo $book['book_id']; ?>">Delete</button></td>
</tr>
<?php endforeach; ?>
</table>
</form>
I think you're having problem with the id that you are passing to your PHP code. Try to use var_dump($_POST) to see what is the content of your $_POST variable. As I can see, the index of $_POST is wrong.
<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:100px" required>';
Try to change this to
<input type="submit" name="book_id" value="$id" style = "width:100px" required>';
In your php use this $_POST["book_id"] to get the value of book_id you posted.
Note : The attribute "name" of the input tags will be the index of your $_POST variable
I understand that you want to have a delete and update button at the same time. The problem is your logic behind the situation. You need to have a hidden field and put the id inside it. Try to use this.
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="hidden" value="$id" name="book_id" id="myAdd" required>';
echo '<input type="submit" value="Update" name="action" id="myAdd" required>';
echo '<input type="submit" value="Delete" name="action" id="$id" required>';
echo '</form>';
In your php code use try to have a condition like this :
$book_id = $_POST["book_id"];
if($_POST["action"] == "delete")
{
//do your deletion code here. use the variable $book_id
}
else{
//do your update code here.use the variable $book_id
}

Getting data to display in a form

I'm trying to use HTML, PHP and MYSQL to pull data from a database and display it in a form (to later be edited). At this point I'm only trying to pull that data and display it in a form. (I'll worry about updating later). I pull the data but nothing displays in my textboxes:
<?php
$con = mysqli_connect("XXXXX"); //removed for privacy
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="select * from VOLUNTEER";
echo '$query';
$result = mysqli_query($con, $query);
echo "<table>";
if ($result)
{
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo '<form method = "post" action="insertvolunteer.php">';
echo '<tr>';
echo '<td>First Name:</td>';
echo '<td>' . '<input type=text name=FirstName' . $row["FirstName"] . '</td>';
echo '<td>' . '<input type=hidden name=VolunteerId' . $row["VolunteerId"] . '</td>';
echo '</tr>';
}
}
echo "</form>";
echo "</table>";
mysqli_close($con);
?>
Text box data needs to be displayed on value as
echo '<td><input type="text" name="FirstName" value="'.$row["FirstName"].'"></td>';
connect.php
<?php
$server = "server";
$user = "user";
$password = "password";
$bd = "yourbd";
$connect = mysql_connect($server, $user, $password);
$connect = mysql_select_db("$bd", $connect);
if (!$connect){
echo mysql_error(); exit;
}
?>
namefile.php
<?php
include('connect.php');
$select = mysql_query("select * from VOLUNTEER");
while ($show = mysql_fetch_assoc($select)):
echo "<table>";
echo "<form method = 'post' action='insertvolunteer.php'>";
echo '<tr>';
echo '<td>First Name:</td>';
echo '<td><input type="text" name="FirstName" value="'.$show["FirstName"].'"></td>';
echo '<td><input type="text" name="FirstName" value="'.$show["VolunteerId"].'"></td>';
echo '</tr>';
echo "</form";
echo "</table>";
endwhile;
?>
When you create an MySQL query, you need to declare this. How?
$var = "SELECT * FROM SOMEWHERE"; wrong
$var = mysql_query("SELECT * FROM SOMEWHERE"); right
'n in echo '<td>' . '<input type=text name=FirstName' . $row["FirstName"] . '</td>';, you need to close the tag. And also have no need of separate <td> of <input>.
Try something like :)
#update I realized that you've got what was wished. Cheers.

Categories