I have been able to display the data from my database on to my website and I'm trying to delete a single row.
Now the button works but it completely deletes everything as you may tell from the code.
I have no idea on how to assign the delete button to a specific row in my table, where it just deletes that data in that specific row.
On top of this I have one delete button that sits upon my table and have no clue on how to set separate delete buttons for each row given.
admin.php (Displaying my data)
<?php
echo "<table style='box'>";
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Role</th>
<th>Email</th><th>Username</th><th>Delete</th><th>Amend</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='box'>" . parent::current(). "</td>";
}
function beginChildren(){
echo "<tr>";
}
function endChildren(){
echo "</tr>";
}
}
require 'connection.php';
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v){
echo $v;
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" action="delete.php">
<input <input class="btn-default" type="submit" name="login" value="Delete">
</form>
<?php
echo "</table>";
?>
delete.php
<?php
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I would show an image but I don't have enough reputation points to display it.
The WHERE clause in your DELETE statement will always return to true. On every row, ID will always equal ID. Hence, everything is deleted. You need to pass a parameter to delete script to filter on the row you want deleted. You can do so by a hidden HTML input value using get="method" of <form>.
However, the key is how to obtain that id from webpage's select query. Additionally, you will want to put the input button at the end of each row to delete the corresponding row's id. For these two items, you might have to return to traditional loop onto web page instead of the RecursiveArrayIterator() because we need to add a non fetched object (form delete button) into table.
admin.php (notice form button as last table cell of each row)
...same code as above...
try {
$stmt = $conn->prepare("SELECT id, FirstName, LastName, Role, Email, Username FROM users");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $result->fetch()) {
?>
<tr>
<td style="box"> <?php echo $row['id']; ?></td>
<td style="box"> <?php echo $row['FirstName']; ?></td>
<td style="box"> <?php echo $row['LastName']; ?></td>
<td style="box"> <?php echo $row['Role']; ?></td>
<td style="box"> <?php echo $row['Email']; ?></td>
<td style="box"> <?php echo $row['Username']; ?></td>
<td>
<form method="get" action="delete.php">
<input type="hidden" name="rowid" value="<?php echo $row['id']; ?>">
<input class="btn-default" type="submit" name="login" value="Delete">
</form>
</td>
<tr>
<?php
}
}
catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
delete.php (notice $id generated from $GET() and used in delete query)
$servername = 'localhost';
$username = 'root';
$pass = 'root';
$database = 'tutor_database';
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// OBTAIN ROWID FROM $_GET
if(isset($_GET['rowid'])) {
$id = $_GET['rowid'];
}
// DELETE SPECIFIED ROW
$sql = "DELETE FROM users WHERE id = ".$id;
$conn->exec($sql);
echo "Record deleted!";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Trying to follow what you have. Have you tried setting the id to a var before doing?
$sql = "DELETE FROM users WHERE id = id";
Example:
$sql = "DELETE FROM users WHERE id = '$id'";
One problem is that your DELETE statement does not include a variable.
//sql to delete record.
$sql = "DELETE FROM users WHERE id = id";
You need something more like:
//sql to delete record.
$sql = "DELETE FROM users WHERE id = " . $id;
where $id is defined with the ID of the selected row.
Let's address another "hidden" problem.
Now the button works but it completely deletes everything as you may tell from the code.
Given the fact that you said this deletes ALL the records, I would guess that the id of each of your rows is the string 'id' and not a unique integer value.
DELETE FROM {table} WHERE id = {number} does not delete ALL records. It only deletes records matching the condition. You should make sure that you are setting id's correctly when adding rows. The id column should have the following properties: INT UNSIGNED NOT NULL AUTO_INCREMENT.
Related
I've spent a lot of time messing around with PHP and MYSQL and I've finally managed to create a "to do list" sort of thing that allows the user to submit a "to do" task and for it to add it to a database and then show it. I've followed many tutorials as I've tried to teach myself PHP blah blah. But for some reason i cannot get the delete script working.
echo "<td><a href='delete.php?=Delete" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
Above is the code for the delete button
Here is the delete script apologies for the many commented out lines I've tried many 'solutions'.
$ID = $_GET['task_id'];
//$delete_query = "DELETE FROM Tasks WHERE ID = $ID" ;
$sql = "DELETE FROM Tasks WHERE task_id = $ID;";
echo $row['task_id'];
// $delete_query = "DELETE FROM Tasks WHERE task_id = ['task_id'] ";
/* if(isset($GET['task_id'])){
$delete = $_GET['task_id'];
mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '$delete'");
} */
echo("Succesfully deleted");
mysqli_close($link);
The script runs and it says "successfully deleted" but the entry still shows. In the F12 Menu/Network tab I get this
error
And when I click "view source" it shows the ID of the row. I can't seem to figure out what is wrong.
I am try to delete data using php pdo. and data can deleted successfully so you can try this code.
I have created 2 file. first req.php and second delete.php.
Here req.php file can fetch data and delete.php file can delete this data from send req.php file id.
req.php
<?php
require "connection.php";
//This is a fetch data from database
$sql = "SELECT * FROM test";
$select = $conn->prepare($sql);
$select->execute();
?>
<html>
<head>
<title>Data</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($data = $select->fetch())
{
?>
<tr>
<td><?php echo $data['id']; ?></td>
<td><?php echo $data['student_name']; ?></td>
<td><?php echo $data['email_address']; ?></td>
<td><button onclick="return conformation();">Delete</button></td> <!-- This is a delete data button --->
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
<script>
//This is a conformation function if it will return true then data can delete otherwise data cannot deleted.
function conformation() {
let conform = confirm("Can you delete this data ?");
if (conform == true) {
return true;
} else {
return false;
}
}
</script>
delete.php
<?php
require "connection.php";
if(isset($_GET['id']))
{
$sql = "DELETE FROM test WHERE id = ?";
$deleteData = $conn->prepare($sql);
if ($deleteData->execute([$_GET['id']]))
{
header('location: http://local.test/req.php');
}
}
?>
The first issue is trying to get task_id from REQUEST params while you sending "Delete" key.
The second is you passed the task_id to db as a string, while I think it's an Integer type in the database.
So you have to do that:
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
$task_id = mysqli_real_escape_string($connect, $_GET['task_id']);
if (!empty($task_id)) {
$delete_query = mysqli_query($connect, 'DELETE FROM Tasks WHERE task_id = '.$task_id);
if ($delete_query) {
echo 'deleted successfully';
} else {
echo("Error: " . mysqli_error($connect));
}
} else {
echo 'task_id is empty !';
}
You can solve this or debug it by doing the following.
parse the right URL parameter
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
this will send a task_id value to the delete page.
checking and logging the response of my SQL in delete.php
if(isset($_REQUEST['task_id'])){
//escape to avoid SQL injection
$delete = mysqli_real_escape_string($connect, $_REQUEST['task_id']);
$process = mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '".$delete."'");
if($process){
echo("Succesfully deleted");
}else{
echo("Error description: " . mysqli_error($connect));
}
}else{
echo("no id supplied");
}
in your question, you also had this: $GET['task_id'], which I believe was null.
I have two tables in one database. The first one is the g1 where the buttons' data is located. The second is the gradeone, where the enrollees' data is located. I want to display the data from the table "gradeone" by clicking the
specific buttons.
Assuming that I added 2 sections. Section 1 and section 2. I click the button section1. By clicking it, I want to display the data of the enrollee from table "gradeone" where the section is 1.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$sectionnumber ="";
$datasuccess ="";
$error ="";
function getPosts(){
$posts = array();
$posts[1] = $_POST['sectionnumber'];
return $posts;
}
if(isset($_POST['add'])){
$data = getPosts();
if(empty($data[1])){
$error = 'Enter The User Data To Insert';
}else {
$insertStmt = $con->prepare('INSERT INTO g1(sectionnumber) VALUES(:sectionnumber)');
$insertStmt->execute(array(
':sectionnumber'=> $data[1]
));
if($insertStmt){
$datasuccess = "<font color='#f8234a'>New added</font>";
}
}
}
?> //Code for adding a button
<?php
require 'connection.php';
$sql = "SELECT sectionnumber FROM g1";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<button type='button' class='btn'>Section " . $row["sectionnumber"] . "</button></a><hr>";
}
} else { echo "<B>No Sections</B>"; }
$con->close();
?> //Code for displaying the button
<html>
<body>
<form action=">
<input type="number" name="sectionnumber">
<input type="submit" name="add">
</form>
</body>
</html>
I outputted the results of a MySQL table to an HTML table, I'm trying to add a Delete button to remove the user but it doesn't work.
HTML form code:
<?php
$response = $bdd->query('SELECT * FROM users');
$i = 1;
while ($datas = $response->fetch()) {
?>
<tr>
<td><?php echo $datas['first_name']; ?></td>
<td><?php echo $datas['last_name']; ?></td>
<td>
<form action="_delete.php?id=<?php echo $datas['id']; ?>" method="post">
<input type="hidden" name="name" value="<?php echo $datas['id'];?>">
<input class="btn btn-danger" type="submit" name="submit" value="X">
</form>
</td>
</tr>
And this is my _delete.php :
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'root', 'root');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
<?php
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
//sends the query
mysql_query ($query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
?>
My result url is good /_delete.php?id=13 but Delete script isn't.
I have this error: Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future
Any idea?
Your messing around with GET and POST params. You defined a get param named id containing your id and a post param named name containing also your id.
But currently you are trying to access the get param with $_POST (which contains only post params).
To solve your problem, you should use $_GET['id'] or $_POST['name'].
In each way, keep in mind to protect you input from sql injections. Currently the user could pass anything else as well. A simple cast to an int, would be enough.
$id = (int)$_GET['id'];
$query = "DELETE FROM users WHERE id={$id} LIMIT 1";
I have incoporated a few suggestions in my answer, try and see if it works.
Create a connection, then get the ID using $_GET instead of $_POST.
<?php
$con=mysqli_connect("localhost","dbuser","dbpassword","dbname");
if($con==false){
die("ERROR:Could not connect.". mysqli_connect_error());
}
else{
$id=$_GET['id']
$query = "DELETE FROM users WHERE id='$id' LIMIT 1";
//sends the query
mysql_query ($con,$query);
if (mysql_affected_rows() == 1) {
?>
<strong>User Has Been Deleted</strong>
<?php
} else {
?>
<strong>Deletion Failed</strong>
<?php
}
}
?>
I am trying to create a button on my user list page to delete that row, or make that user an admin.
Here is the info for the user query and html:
<?php
$query = "SELECT * FROM users";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row) : ?>
<?php
if($row['usertype'] == 2) {
$usertype = "<span style='color:#F7FE2E;'>Donator</span>";
} elseif($row['usertype'] == 3) {
$usertype = "<span style='color:red;'>Admin</span>";
} elseif($row['usertype'] == 4) {
$usertype = "<span style='color:orange;'>Owner</span>";
} else {
$usertype = "<span style='color:#585858;'>Normal</span>";
}
?>
<tr>
<!--<td><?php echo $row['id']; ?></td>-->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<!--<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8');?></td>-->
<td><?php echo htmlentities($row['steamid'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo $usertype?></td>
<td><form action="" method="post">
<input type="submit" name="admin" value="Promote" />
</form></td>
</tr>
<?php endforeach; ?>
And the code where I prepare and execute my update query:
if(!empty($_POST['admin']))
{
$query = "UPDATE `users` SET `usertype` = '3' WHERE `id` = " . $row['id'];
// $query_params = array(':id' => $row['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
}
Unfortunately I when I run this current setup, it updates the very last row. To further ask what I am looking for, is I have a list of users:
where "admin_b" is a button that forced $_POST['admin']
Billy admin_b
Bob admin_b
Jill admin_b
Jack admin_b
UPDATE:
So in my form I have an input with <input type="hidden" name="id" value="<?php $row['id']; ?>" /> and added this to my SQL $query = "UPDATE users SET usertype = '3' WHERE id = :id"; $query_params = array(':id' => $_POST['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
send an id with $_POST request, now you are always update user with id = $row['id']
WHERE `id` = " . $row['id'];
row[id]edit?=edit.php= ...
and let's say you have list all the members and beside them is an href, the code above will execute, it will display let's say Billy?edit.php=1, wherein 1 is his primary key, then for the next, when you scroll the cursor to the next href of the next user, Jim, it will display, Jim?edit.php=2, in your edit.php,
if(isset($_POST['edit])){
code goes here to make the user an admin..
You can also make an href for the delete, similar to this edit..
This is just an idea/hint that I can give to you, but your problem can be solved in many different ways, it just depends on your approach on how you could do it :D goodluck.
i'm farly new to php and are trying to make a php script where it's suppose to connect to a mysql db and get the vaule id, then show as an option in a drop down menu.
This is the code I have so far (got help from a friend):
$username = "root";
$password = "";
$hostname = "localhost";
$database = "customers";
$id = "";
mysql_connect("$hostname", "$username", "$password") or die (mysql_error()) or die (mysql_error());
mysql_select_db("$database") or die (mysql_error());
$result = mysql_query("SELECT id FROM users WHERE id='$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$valuestring = $row['id'];
print_r($result);
echo "<option value='$valuestring'>". $valuestring ."</option>";
mysql_close();
}
print_r($id);
But when I use this code the option is returned empty :/
I have also tried to do print_r($result); and that give me Resource id #4, so I guess that works.
If anyone could help me solve this I would be one happy guy :D
the $id value in your code is empty, are you avare of that ?
and can you print the query before sending it to mysql ?
use :
"$query = "select id from table where id = '$id'";
mysql_query($query);
echo $query;
Perhaps if you showed us what output you did get it would help.
the option is returned empty
If the output includes HTML generated inside the loop then that means the query returned at least 1 row. But the only way that echo "<option value='$valuestring'>" would produce an empty string is if $valuestring was an empty string. It's populated from "SELECT id FROM users WHERE id='$id'" implying that you must have a row in your database where id is null or an empty string and $id in your php code is null/empty string - indeed that is the case ($id = "";).
NTW the mysql_close(); should be outside the loop.
Let's simplify this code:
<select name="user" id="user" width="200px" style="width: 200px">
<option value="">Select State</option>
<?php
$query_uf = "SELECT id FROM users WHERE id="'.$id.'";
$result = mysql_query($query_uf,$bd);
while ($users =mysql_fetch_assoc($result)) {
echo "<option value='".$uf['id']."'>".$uf['user']."</option>"; }
?>
</select>
Obs: It's better you use mysqli_query and connect. And, in your code it's missing the connection in mysql_query.
I've previously needed to retrieve a list of albums from a table using a similar method, maybe try this function. Create your form and call the function within the and tags leading this to work. This should list your id(s) where specified in the query.
functions.php (or wherever you'd like to put the function):
function stateList() {
$username = "username";
$password = "password";
$host = "localhost";
$dbname = "dbname";
$id = RETRIEVE VALUE HERE;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "
SELECT
id,
FROM users
WHERE
id = $id // YOU MAY WANT TO REMOVE WHERE - $ID AS STATED ABOVE, DOESN'T MAKE SENSE.
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$valuestring = $row['id'];
$rows = $stmt->fetchAll();
foreach($rows as $row):
print "<option value='" . $valuestring . "'>" . $valuestring . "</option>";
endforeach;
}
?>
Selection page:
<? include 'functions.php' ?> <!-- This will allow you to call the function. -->
<form action="example.php" method="post" enctype="multipart/form-data">
<select name="album">
<? stateList(); ?> <!-- Calls the function and retrieves all options -->
</select>
<input type="submit" name="submit" value="Submit">
</form>