l have created an application using php,html and mysql. The application can store a user's information such as id, name, bio, and date created into the database and display in html table. The id is an auto increment value which increases with every data entered by the user. The insert part of the application works fine but when l try to delete a record nothing happens. An html form is part of the code which l have intentionally decided not to include. Here is a snapshot of my code:
$records = array();
if(!empty($_POST)) {
if(isset($_POST['firstName'],$_POST['lastName'], $_POST['bio'])){
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$bio = trim($_POST['bio']);
if(!empty($firstName) && !empty($lastName) && !empty($bio)) {
$insert = $db->prepare("INSERT INTO people (firstName, lastName,
bio, created) VALUES (?, ?,?, NOW())");
$insert->bind_param('sss', $firstName, $lastName, $bio);
if($insert->execute()){
header('Location: addressbook.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM people")){
if($results->num_rows){
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class = "container">
<?php
if(!count($records)){
echo 'No records found';
}
else{
?>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Bio</th>
<th>Created</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
foreach ($records as $r) {
?>
<tr>
<td><?php echo escape($r->id);?></td>
<td><?php echo escape($r->firstName); ?></td>
<td><?php echo escape($r->lastName); ?></td>
<td><?php echo escape($r->bio); ?></td>
<td><?php echo escape($r->created); ?></td>
<td>
<a onclick="return confirm('Do you want to delete the
record')" href="addressbook.php?idd=<?php echo $row['id'] ?>"
class="btn btn-
danger">Delete</a></td>
<?php
}
?>
</tr>
//My guess is the problem is with this code down here for deleting
<?php
if(isset($_POST['idd'])){
$idd = $_POST['idd'];
$results = $db->query("DELETE FROM people WHERE id=$idd");
if($results){
header('Location: addressbook.php');
}
}
?>
</tbody>
</table>
<?php
}
?>
you need to use $_GET because by default href tag sends the data with GET method.
your code should be
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='$idd'");
if($results){
header('Location: addressbook.php');
}
}
NOTE- use prepared statement for avoiding sql injection attack
`
<?php
//database connectivity
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"<db_name>");
$idd = $_REQUEST['idd'];
$sql= "DELETE FROM people WHERE id='$idd' ";
$result = mysqli_query($con,$sql) or die(mysql_error());
header("refresh:0.1; addressbook.php");
?>`
if(isset($_GET['idd'])){
$idd = $_GET['idd'];
$results = $db->query("DELETE FROM people WHERE id='{$idd}'");
Try adding a single quote.
If it still doesn't work, please see if the $_POST is actually posting correctly.
Try $results = $db->query("DELETE * FROM people WHERE id=$idd"); instead of $results = $db->query("DELETE FROM people WHERE id=$idd"); in the delete User Function :)
Related
right now I have a page which displays homework set by teachers from a database. The students must be able to see all their homework on this page, with the due date and set date. As of now, it's working and after the due date, the task turns red, which is fine. However, I need to now add a small box or button which can be clicked by the student once they have completed the task. Once this is done, It would delete it ONLY for the student which has clicked it.
<?php
include_once("connection.php"); //including the database connection file
$id= $_GET['id'];
$result = $conn->prepare("SELECT * FROM homework WHERE class_id=? ORDER BY datedue DESC");
$result->bind_param("i", $id);
$result->execute();
$result2 = $result->get_result();?>
<html>
<head>
<title>View IS</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
<td><button type="button">Click Me!</button></td>
</tr>
<?php
while($res = mysqli_fetch_array($result2)) {
if (strtotime(date("d-m-Y")) > strtotime($res['datedue'])) {
echo "<tr style=\"color: red;\">";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
echo "<td>".<button type=button>Click Me!</button>."</td>";
echo "</tr>";
} else {
echo "<tr>";
echo "<td>".$res['description']."</td>";
echo "<td>".$res['dateset']."</td>";
echo "<td>".$res['datedue']."</td>";
echo "<td>".<button type=button>Click Me!</button>."</td>";
echo "</tr>";
}
}
?>
</table>
</body>
How can I do this? Thank you
I couldn't test this, can you give this a try and let me know if error occurs
create new field name 'stud_completed' in homework table
homework.php page
<?php
include_once("connection.php"); //including the database connection file
$id = $_GET['id'];
$result = $conn->prepare("SELECT * FROM homework WHERE class_id=? ORDER BY datedue DESC");
$result->bind_param("i", $id);
$result->execute();
$result2 = $result->get_result();
$todayDate = strtotime(date("d-m-Y"));
$Log_student = $_SESSION['studentID'];
?>
<html>
<head>
<title>View IS</title>
</head>
<body>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Task</td>
<td>Date Set </td>
<td>Date Due </td>
<td>Action</td>
</tr>
<?php
while($res = mysqli_fetch_array($result2)) {
$redDueTask = null; // each loop $redDueTask will be set to NULL
$homeworkID = $res['id']; // Get the DueDate of each task
$dueDate = strtotime($res['datedue']); // Get the DueDate of each task
if ($todayDate > $dueDate) { $redDueTask = 'style="color: red;"'; } // Set $redDueTask if task has past duedate
$student_completed = explode(',',$res['stud_completed']); // get the coma seperated completed student list and convert it to array
if (!in_array($Log_student, $student_completed)) { // chk if logged in student ID is in array and if not in the list show task
?>
<tr <?php echo $redDueTask?>>
<td><?php echo $res['description']?></td>
<td><?php echo $res['dateset']?></td>
<td><?php echo $res['datedue']?></td>
<td>
<?php if (isset($redDueTask)) { // $redDueTask will bset if the task duedate has passed, so no need compelete button ?>
Time UP!
<?php } else { // $redDueTask is not set then show compelete button ?>
<button type='button'>Have Complete</button>
<?php } ?>
</td>
</tr>
<?php
}
}
?>
</table>
</body>
taskdone.php page
<?php
include_once("connection.php"); //including the database connection file
$tid = $_GET['tid']; // Get Homework Task ID from URL
$Log_student = $_SESSION['studentID']; // Get Loggedin Student ID from Session
// Get ROW Statment
$result = $conn->prepare("SELECT * FROM homework WHERE id=?");
$result->bind_param('i', $tid);
$result->execute();
$result2 = $result->get_result();
$res = mysqli_fetch_array($result2);
$stud_completed = $res['stud_completed']; // Get the current List of completed student
if ($stud_completed == "") { // If stud_completed is null or blank
$stud_completed = $Log_student; // add the current student ID with out coma
} else {
$stud_completed .= "," . $Log_student; // Inculde the current logged in student ID with coma
}
// Update ROW Statement
$sql = "UPDATE homework SET stud_completed=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $stud_completed, $tid);
if ($stmt->execute()) {
header("homework.php"); // if GOT updated go to home work task list page
}
?>
I need to add a form input to search for a second column in a table.
I have tried adding a form. Tried manually putting what I am looking for in the SELECT line and it finds the data. Just need to be able to find it with form input.
<?php
/**
* Mark as Paid
*/
require "../config.php";
require "../common.php";
$success = null;
if (isset($_POST["submit"])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST["submit"];
$sql = "UPDATE consignsold SET paid='y' WHERE paid='n' AND sold='y' AND itemnumber = $itemnumber";
$statement = $connection->prepare($sql);
$statement->bindValue(':itemnumber', $itemnumber);
$statement->bindValue(':paid', $paid);
$statement->bindValue(':sold', $sold);
$statement->execute();
$success = "Item successfully updated";
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
try {
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * FROM consignsold WHERE paid='n'";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
?>
<?php require "templates/header.php"; ?>
<h2>Mark Items as Paid</h2>
<?php if ($success) echo $success; ?>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<table>
<thead>
<tr>
<th>Sale Number</th>
<th>Item Number</th>
<th>Lot Number</th>
<th>Category</th>
<th>Item Description</th>
<th>Reserve</th>
<th>Seller Number</th>
<th>Amount</th>
<th>Buyer Number</th>
<th>Sold</th>
<th>Paid</th>
<th>Mark</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) : ?>
<tr>
<td><?php echo escape($row["salenumber"]); ?></td>
<td><?php echo escape($row["itemnumber"]); ?></td>
<td><?php echo escape($row["lotnumber"]); ?></td>
<td><?php echo escape($row["category"]); ?></td>
<td><?php echo escape($row["itemdescription"]); ?></td>
<td><?php echo escape($row["reserve"]); ?></td>
<td><?php echo escape($row["sellernumber"]); ?></td>
<td><?php echo escape($row["amount"]); ?></td>
<td><?php echo escape($row["buyernumber"]); ?></td>
<td><?php echo escape($row["sold"]); ?></td>
<td><?php echo escape($row["paid"]); ?></td>
<td><button type="submit" name="submit" value="<?php echo escape($row["itemnumber"]); ?>">Mark as Paid</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</form>
<br>
<?php require "templates/footer.php"; ?>
If I try to add a form, I get a blank page. I expect a form with a place to input Buyer Number. As-is, the page works but displays all items and the operator has to manually find each item by buyer number and click the Mark as Paid button. What I need it to do is have an input where it asks for buyer number and only list those items with the mark button at the end. It is a closed-circuit operation so not worried about injections at this time.
The line: $sql = "SELECT * FROM consignsold WHERE paid='n'";
would be changed to something like: $sql = "SELECT * FROM consignsold WHERE paid='n' AND buyernumber = <from form input>";
Some have asked to clarify. . . I thought it was pretty clear to start with but. . .
REVISION: What I need on that page is a form input that asks the operator for a buyernumber and then uses the input from that form in the SELECT line to look for buyernumber and sold = 'y'. "buyernumber" is a column and "sold" is a column in the table: consignsold.
Thanks again to all who try to help!
I am not entirely sure, I understand your question, but let me answer what I see is wrong.
First of all you should not catch the exceptions. This is considered a bad practice.
You also do not need 3 binds, you can just pass $itemnumber in the execute(). For this however you need to put a placeholder in the query. ? is simpler than a named placeholder.
$connection = new PDO($dsn, $username, $password, $options);
$itemnumber = $_POST["submit"];
$sql = "UPDATE consignsold SET paid='y' WHERE paid='n' AND sold='y' AND itemnumber=?";
$statement = $connection->prepare($sql);
$statement->execute([$itemnumber]);
$success = "Item successfully updated";
I have pagination for a table to display data from the database in the table. This was working fine and I tried to add in a button which only admin's can see. If the user is not an admin they will not see this button. This feature works but once I did it, the pagination only shows one row of data compared to the maximum of 10 per page.
This is my code:
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0) // display records if there are records to display
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$poll_id = $row['poll_id'];
$question = $row['question'];
?>
<tr>
<td><?php echo $row['poll_id']; ?></td>
<td><?php echo $row['question']; ?></td>
<td>Open Poll</td>
<td>Results</td>
<?php
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(':user_id'=>$_SESSION['user_session']));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0){
$admin = $userRow['admin'];
if($admin == 1){
?>
<td>Delete Poll</td>
<?php
?>
</tr>
<?php
}
}
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
and this is the code on the html page which uses the pagination
<table align="center" border="1" width="100%" height="100%" id="data">
<?php
$query = "SELECT * FROM polls";
$records_per_page=10;
$newquery = $paginate->paging($query,$records_per_page);
$paginate->dataview($newquery);
$paginate->paginglink($query,$records_per_page);
?>
</table>
You are reusing variables like $stmt inside the loop that uses it. So do this:
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0) // display records if there are records to display
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$poll_id = $row['poll_id'];
$question = $row['question'];
?>
<tr>
<td><?php echo $row['poll_id']; ?></td>
<td><?php echo $row['question']; ?></td>
<td>Open Poll</td>
<td>Results</td>
<?php
$stmt2 = $this->db->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt2->execute(array(':user_id'=>$_SESSION['user_session']));
$userRow=$stmt2->fetch(PDO::FETCH_ASSOC);
if($stmt2->rowCount() > 0){
$admin = $userRow['admin'];
if($admin == 1){
?>
<td>Delete Poll</td>
<?php
?>
</tr>
<?php
}
}
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
I have replace the $stmt inside the loop by $stmt2.
My idea is to click 'Delete' link and it will pass the id to another PHP page (deleteSession.php), and then execute the query in deleteSession.php. but I couldn't seems to get the id from manageSession.php
In manageSession.php,
<table align='center' border='1' cellpadding='5' cellspacing='0'>
<tr>
<th>Session Id</th>
<th>Type</th>
<th>Date & Time</th>
<th>Venue</th>
<th>Pax</th>
<th>Delete</th>
<th>Edit</th>
</tr>
<?php
$sql = "SELECT booking_id, booking_types, dates_sessions, venue_available, room_count FROM bookings_available ORDER BY dates_sessions asc";
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
//mysqli_close($link);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['booking_id']; ?></td>
<td><?php echo $row['booking_types']; ?></td>
<td><?php echo $row['dates_sessions']; ?></td>
<td><?php echo $row['venue_available']; ?></td>
<td><?php echo $row['room_count']; ?></td>
<td><input type="button" value="Delete"/></td>
<td><input type="button" value="Edit"/></td>
</tr>
<?php } ?>
</table>
In deleteSession.php,
<?php
include "dbFunctions.php";
include "manageSession.php";
//$sql = "SELECT booking_id, booking_types, dates_sessions, venue_available, room_count FROM bookings_available";
//$result = mysqli_query($link, $sql) or die(mysqli_error($link));
$bookingId = filter_input(INPUT_GET, 'booking_id');
$deleteQuery = "DELETE FROM bookings_available WHERE booking_id = '$bookingId'";
?>
I think in deleteSession.php file code should be as follows.
$bookingId = filter_input(INPUT_GET, 'id');
OR
$bookingId = $_GET['id'];
Because you are passing get parameter as follows.
deleteSession.php?id=
And also keep anchor as follows.
Delete
In the deleteSession.php you can try and replace:
$bookingId = filter_input(INPUT_GET, 'booking_id');
with the below code:
$bookingId = $_REQUEST['id'];
Finally at the last line you have to execute the query which is stored in $deleteQuery variable, which is not executed yet by using below code:
$qry = mysql_query("DELETE FROM bookings_available WHERE booking_id = '$bookingId'");
//will show you error if not able to delete
if(!$qry)
die("Error: ".mysql_error());
Added this at line 3 and it works:
mysqli_select_db($link ,$DB);
Because in the code I have not selected the mysql database and also the query was not executing as the first parameter $link was missing.
I've recently made a PHP, that should; if click a link delete a certain row within one of my MYSQL tables.
The script below has everything but the link [href=delete_ac.php?id etc...] leads to the page but when the page activates it echo ERROR instead of deleting the row.
<h1>Members</h1>
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>E-Mail Address</th>
<th></th>
</tr>
<?php foreach($rows as $row): ?>
<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>delete</td>
</tr>
<?php endforeach; ?>
</table>
delete_ac.php
The script below is what should delete it but it isn't
<?php
require("../php/bp-connectionAdmin.php");
$id=$_GET['id'];
$query = "DELETE FROM `users` WHERE `id` = $id";
$result = mysql_query($query);
if ($result) {
echo "Successful";
} else {
echo "ERROR";
}
?>
Is the ID numeric only? Would the addition of quote marks around $id not help?
$query = "DELETE FROM `users` WHERE `id`='$id'";
mysql_query($query);
Not sure...but give it a go!
Put on the line after $query = "DELETE ..
An
echo "DELETE FROM `users` WHERE `id` = $id";
die;
Then you will see what goes wrong.
Personally i would remove the ', assuming that the id=integer, and you will have:
$query = "DELETE FROM users WHERE id=$id";
If not, try that echood query directly in your Database window and you will see what is wrong.
Most probably you should change your line into
$id=intval($_GET['id']);
which is also much more secure!