I was trying to delete a record on my Database. So basically I created a table that contains all of my records. Now what I need to do is when I click on the "DELETE" link it would delete the record selected row.
Here's what it looks like:
So basically I have 3 pages here.
1. page.php
2. add.php
3. delete.php
Here's my page.php file:
<table border="1">
<thead>
<th>email</th>
<th>date</th>
<th>delete</th>
</thead>
<tbody>
<tr>
<?php
foreach($emails as $mail){ ?>
<td><?php echo $mail['email']; ?></td>
<td><?php echo $mail['date']; ?></td>
<td><?php echo "<a href='delete.php?id=". $mail['id']. "'>DELETE</a>"; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's my add.php file:
<?php
require("new-connection.php");
session_start();
$email = $_POST['email'];
if(empty($_POST['email']) AND (filter_var($email, FILTER_VALIDATE_EMAIL) === false))
{
$_SESSION['message'] = "email cannot be blank";
}else{
$query = "INSERT INTO email_tbl (email, date)
VALUES('$email', NOW())";
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
else
{
$_SESSION['message'] .= "Failed to add new Interest";
}
}
header('Location: email.php');
?>
Here's my delete.php file so far:
<?php
require("new-connection.php");
session_start();
$query = "DELETE FROM email_tbl
WHERE id={id} LIMIT 1";
$deleteEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
So now when I click the delete link it must delete the button real time. Any idea?
Modify your delete.php to retrieve the url parameter:
<?php
require("new-connection.php");
session_start();
$id = $_GET['id'];
$query = "DELETE FROM email_tbl
WHERE id='$id' LIMIT 1";
$deleteEmail = run_mysql_query($query);
if($deleteEmail)
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
As for your add.php, you are using this:
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
You should change it to this:
$insertEmail = run_mysql_query($query);
if($insertEmail)
What you are doing right now is you are executing the query twice by calling run_mysql_query twice. This should fix it
Sense when what run_mysql_query a function in php?
http://php.net/manual-lookup.php?pattern=run_mysql_query&scope=quickref
Update the delete.php file:
$id = $_GET['id'];
$query = "DELETE FROM email_tbl WHERE id='$id' LIMIT 1";
and also check the section below:
You are running the query twice. so it is obvious it will add the same record twice.
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
Modify you code to use the run_mysql_query once only.
$query = "DELETE FROM email_tbl WHERE id=".$_GET['id']." LIMIT 1";
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 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.
Below is my php code that caries out the redirection
Code Snippet :-
echo "<form action='exp_yogesh.php?id=$id' method='post'>";
echo "<td> <input type='image' name='putonline' value='$id' src='images/on_button.png' no-repeat; border:none;' alt='submit'> </td> ";
echo "<td> <input type='image' name='putoffline' value='$id' src='images/off_botton.png' no-repeat; border:none;' alt='submit'> </td> ";
echo "</form>";
Here's the exp_yogesh.php file
<?php
include 'includes/connection.php';
session_start();
$new_id= $_GET['id'];
if (isset($_POST['putonline'])) {
$query = "UPDATE user SET status= '1' WHERE id= '$new_id'";
$result = $cid-> query($query);
if ($result== TRUE) {
header("Refresh:0.01; url=EidtEmp.php");
exit;
} else {
echo "";
}
}
if (isset($_POST['putoffline'])) {
$query = "UPDATE user SET status= '0' WHERE id= '$new_id'";
$result = $cid-> query($query);
if ($result== TRUE) {
header("Refresh:0.01; url=EidtEmp.php");
exit;
} else {
echo "not done";
}
}
mysqli_close($cid);
?>
The above code works properly when I run it on Google Chrome but doesn't when I do the same on Firefox
have you tried using
header('location') function?
example :
<?php
if (isset($_POST['putonline'])) {
$query = "UPDATE user SET status= '1' WHERE id= '$new_id'";
$result = $cid-> query($query);
if ($result== TRUE) {
header("location:EidEmp.php");
die();
} else {
echo "Failed";
}
}
?>
Edited :
Maybe Change Your header function with javascript function
i.e
echo "<script>window.location.replace('EidtEmp.php');</script>";
or try to change
if (isset($_POST['putonline']))
with
if ($_SERVER['REQUEST_METHOD'] == 'POST' )
because Some browsers do not sent the submit button if you hit enter
UPDATED : Try this if you have two conditions
<?php
include 'includes/connection.php';
session_start();
$new_id= $_GET['id'];
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
if (isset($_POST['putonline_x'])) {
$query = "UPDATE user SET status= '1' WHERE id= '$new_id'";
$result = $cid-> query($query);
if ($result== TRUE) {
header("Refresh:0.01; url=EidtEmp.php");
exit;
} else {
echo "";
}
}
if (isset($_POST['putoffline_x'])) {
$query = "UPDATE user SET status= '0' WHERE id= '$new_id'";
$result = $cid-> query($query);
if ($result== TRUE) {
header("Refresh:0.01; url=EidtEmp.php");
exit;
} else {
echo "not done";
}
}
}
mysqli_close($cid);
?>
Replace top two lines of exp_yogesh.php page.
<?php
include 'includes/connection.php';
session_start();
With
<?php
ob_start();
session_start();
include 'includes/connection.php';
Change your headers functions to:
header("location:EidtEmp.php");
Try this; it might work.
echo("<meta http-equiv='refresh' content='0';url=EidtEmp.php>");
table name -- breaking_news
field name -- status
I have created a single page and passes id from link click.
Now I check if status not empty and status equal to Inactive
then update status = Active Else update status Inactive
but it is not working properly.
It Only Works For If Condition.
The ELSE Condition of Code is Not Working . plz suggest me how to write in if else properly...
<td><img src="img/active.png" width="24" height="24" border="0" title="Active" /></td>
<?php
$Admin = new admins;
$sql = "SELECT status FROM breaking_news WHERE id=".mysql_real_escape_string($_GET['status_active']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(!empty($row) && $row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
?>
Try this code
">
<?php
$Admin = new admins;
$sql = "SELECT status FROM breaking_news WHERE id=".mysql_real_escape_string($_GET['status_active']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(!$row && $row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
?>
you have just to ask if $row was have more or not, be cause mysql_fetch_assocreturn false if it's empty look to this manual : mysql_fetch_assoc PHP
you have just do not use empty()
Or like that :
if($row = mysql_fetch_assoc($result))
{
if($row['status']=='Inactive')
{
mysql_query("Update breaking_news SET status='Active' WHERE id=".mysql_real_escape_string($_GET['status_active']));
$_SESSION['message'] = "Status Activated Successfully";
header("Location:breaking_news.php");
exit;
}
}
else
{
mysql_query("Update breaking_news SET status='Inactive' WHERE id=".mysql_real_escape_string($_GET['status_inactive']));
$_SESSION['message'] = "Status De-Activated Successfully";
header("Location:breaking_news.php");
exit;
}
If you have not found a row, there is nothing to update...
You may wish to do something like this:
<?php
if (!empty($row)) {
if ($row['status'] == 'Inactive') {
//update to active
}
else if ($row['status'] == 'Active') {
//update to inactive
}
}
also you've got a typo in the second call to $_GET array: $_GET['status_inactive']. You should be updating the same row but with different status value.
EDIT
#toto21 I don't have enough reputation to comment on your answers but no, your answer is wrong. As I mentioned at the top - if there is no row fetched then there is nothing in the db for you to update, so your else statement makes no sense.
The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html