Php Delete item from mysql data base - php

Hope some one can help me out here, i guess am not calling my functions right.
Am trying to retrieve some data from my database and have a delete link attached to each items being retrieved, so that when ever i click on delete, it will delete that particular item which have the delete function.
My Code to retrieve items from database are as follows.
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
And my code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = $_GET['id'];
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
header("Location: vacct.php");
?>
I know am missing out the logic here and hope somebody can direct me or show me the easy way out. at the moment i can successfully retrieve my items from the data base my only problem is to be able to apply the delete function each time the delete button is tapped.

You have to pass the id when you click on the delete link:
<a href=\"delete.php?id=$z[theIdKey]\">

Use the below code.I have added validation and encryption
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = base64_decode($_GET['id']);
if(!empty($id)){
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
}
header("Location: vacct.php");
?>

<td>delete</td>
How are you passing the id to delete to your delete.php script?

Change:
<td>delete</td>
to:
<td>delete</td>
if $z[0] is the ID.
In your delete.php, make sure you also escape the word "transaction" using backtick:
DELETE FROM `transaction` WHERE id=123
this is because "transaction" is a reserved mysql keyword.
Please also read on SQL Injections.

Related

Select an sql field from html field and show it in another page

I have displayed sql table in html table, made a hyperlink near all fields, when i click it the whole field details should be shows in other page(ie; i show only 2 fields of sql in the table and want to show rest in another page).
admin.php
<?php
$con= mysql_connect("localhost","root","");
mysql_select_db("main",$con);
echo"<form action=\"post\" class=\"form-horizontal\" role=\"form\">";
echo "<table width='700' height='150' onclick='myFun(event)'>";
echo" <tr>
<td width='100' align='center'></td>
<td width='100' align='center'><b><u>NAME</u></b></td>
<td width='100' align='left'><b><u>E-MAIL</u></b></td>
</tr>
";
$result=mysql_query("select NAME,EMAIL from admin order by AID");
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo"<td width='100' align='center'><a href='viewadmin.php?name=".$row['NAME']."'>Select</a></td>";
echo"<td width='100' align='center'>".$row['NAME']."</td>";
echo"<td width='100' align='left'>".$row['EMAIL']."</td>";
echo"</tr>";
}
echo"</table>";
echo"</form> ";
?>
viewadmin.php
<?php
$name = $_GET['name'];
$result=mysql_query("SELECT NAME,DOB,MOB,EMAIL, FROM admin WHERE NAME = $name");
if (false === $result) {
echo mysql_error();
}
else {
$row=mysql_fetch_row($result);
}
echo" <form class=\"form-horizontal\" role=\"form\">
<table width='400'>
<tr>
<td align='left'>Name</td>
<td align='left'>".$row['NAME']."</td>
</tr>
<tr>
<td align='left'>E-mail</td>
<td align='left'>".$row['EMAIL']."</td>
</tr>
<tr>
<td align='left'>D.O.B</td>
<td align='left'>".$row['DOB']."</td>
</tr>
<tr>
<td align='left'>Mobile</td>
<td align='left'>".$row['MOBILE']."</td>
</tr>
<tr>
<td align='left'>Photo</td>
<td ><img src='uploads/grumpy.jpg' height='200' width='200'></td>
</tr>
</table>";
echo"</form> ";
?>
do something like this:
admin.php
$result=mysql_query("select NAME,EMAIL from admin order by AID");
while($row=mysql_fetch_array($result)) {
echo "<tr>";
echo"<td width='100' align='center'><a href='viewadmin.php?name=".$row['NAME']."'>Select</a></td>";
echo"<td width='100' align='center'>".$row['NAME']."</td>";
echo"<td width='100' align='left'>".$row['EMAIL']."</td>";
echo"</tr>";
}
echo"</table>";
and in viewadmin.php
$name = $_GET['name'];
$result=mysql_query("SELECT * FROM admin WHERE name = $name");
$row=mysql_fetch_row($result);
echo " <form class=\"form-horizontal\" role=\"form\">
<table width='400'>
<tr>
<td align='left'>".$row['NAME']."</td>
<td align='left'></td>
</tr>
<tr>
<td align='left'>".$row['EMAIL']."</td>
<td align='left'>...";
first rename the html page by php page, then you can pass the primary key or any key of the row from first page to admin page with the help of GET.
for eg:
first.php
<?php
$result=mysql_query("select ID,NAME,EMAIL from admin order by AID"); while($row=mysql_fetch_array($result)){
?><a hre='admin.php?id="$id=<?php $row[0] ?>"'></a>
<?php
}
?>
and in the admin.php page
you can access the value like
echo $_GET['id'];
stop using MySQL and use MySQLi, this code should work
<?php
$db_connect = mysqli_connect('localhost', 'root', 'pass', 'database');
if (mysqli_connect_errno($db_connect)) {
die('Some error occurred during connection to the database');
}
$name = mysqli_real_escape_string($db_connect,$_REQUEST['name']);
if($stmt = mysqli_prepare($db_connect, 'SELECT * FROM admin WHERE name = ?')){
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) !== 0){
$row = mysqli_fetch_assoc($result);
echo "<form class=\"form-horizontal\" role=\"form\">
<table width='400'>
<tr>
<td align='left'>".$row['NAME']."</td>
<td align='left'></td>
</tr>
<tr>
<td align='left'>".$row['EMAIL']."</td>
<td align='left'>..."
}
else{
echo 'not found';
}
}
else{
trigger_error('error:' . mysqli_errno($db_connect) . mysqli_error($db_connect));
}
?>

Updating a row of SQL with html table

I have the following code:
$sql = "SELECT * FROM Tickets WHERE stat='Open'";
$result = mysql_query($sql);
mysql_close($con);
?>
<!DOCTYPE>
<html>
<body>
<table class="striped">
<tr class="header">
<td>Username</td>
<td>Title</td>
<td>Description</td>
<td>Admin Name</td>
<td>Category</td>
<td>Status</td>
<td>Urgency</td>
<td>Time In</td>
<td> </td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[username]."</td>";
echo "<td>".$row[title]."</td>";
echo "<td>".$row[description]."</td>";?>
<td><select>
<?php
echo "<option value'".$row[admin_name]."'>".$row[admin_name]."</option>";
$sql = mysql_query("SELECT username FROM Users WHERE user_type='admin'");
while ($u = mysql_fetch_array($sql)){
echo "<option value='".$u['username']."'>".$u['username']."</option>";
}
?>
</select></td>
<?php
echo "<td>".$row[category]."</td>";
echo "<td>".$row[stat]."</td>";
echo "<td>".$row[urgency]."</td>";
echo "<td>".$row[time_in]."</td>";
echo "<td><a href='close.php'>Close Ticket</a></td>";
echo "</tr>";
}
?>
</table>
<a href='update.php'>Update</a>
</body>
</html>
I have two links on this page. Both of them need to update a SQL database. The Close ticket link needs to just update the single row, while the update link should update all of them. I am not sure how to get the info from one php to the next. It seems like you can put the individual row information into a Post array for the close ticket link, but I am not sure how. For the update link it needs to take the value of the dropdown in the table and change the admin_name field to that value.

How can I delete the selected record in mySQL from my HTML/PHP page?

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.

viewing a table based on a previous id

I have a table set up called Modules, that once a user is logged in it brings up the modules related to that user, this works fine. At the side of each module in the table I have a lessons link. once the user clicks on that I want it to display the lessons based on the module ID.
Any help would be great full.
My Module code in case I need to add something to it is as follows;
<?
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Connect to the database
connect();
$userID = $_SESSION['userID'];
$sql = "SELECT * FROM tblModule WHERE userID = '$userID'" ;
$result = #mysql_query($sql) or die(mysql_error());
?>
and displaying the module table as follows;
<?php
// run a while loop through all records and create a new row for each one
while ($record = mysql_fetch_object($result))
{
?>
<table class="myTable">
<th class="col">Module ID</th>
<th class="col">Module Title</th>
<th class="col">Module Description</th>
<th class="col">User ID</th>
<th class="col">Manage</th>
</tr>
<tr class="row">
<td class="cell"><?php echo $record->moduleID; ?></td>
<td class="cell"><?php echo $record->moduleTitle; ?></td>
<td class="cell"><?php echo $record->moduleDescription; ?></td>
<td class="cell"><?php echo $record->userID; ?></td>
<td class="cell">Lessons</td>
</tr>
</table>
<?
}
// clean up after ourselves by cleating $result and closing the database connection
mysql_free_result($result);
mysql_close();
?>
Then so far in the lesson table i have;
<?
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Connect to the database
connect();
$moduleID = $_SESSION['moduleID'];
$sql = "SELECT * FROM tblLessons WHERE moduleID = '$moduleID'" ;
$result = #mysql_query($sql) or die(mysql_error());
?>
With the result been displayed as;
<?php
// run a while loop through all records and create a new row for each one
while ($record = mysql_fetch_object($result))
{
?>
<table class="myTable">
<th class="col">LessonID</th>
<th class="col">Lesson Number</th>
<th class="col">Lesson Description</th>
<th class="col">ModuleID</th>
<th class="col">Lesson Plan ID</th>
<th class="col">Manage</th>
</tr>
<tr class="row">
<td class="cell"><?php echo $record->lessonID; ?></td>
<td class="cell"><?php echo $record->lessonNumber; ?></td>
<td class="cell"><?php echo $record->lessonDescription; ?></td>
<td class="cell"><?php echo $record->moduleID; ?></td>
<td class="cell"><?php echo $record->lessonPlanID; ?></td>
</tr>
</table>
<?
}
// clean up after ourselves by cleating $result and closing the database connection
mysql_free_result($result);
mysql_close();
?>
You're passing the moduleID as a query string variable to lessons.php, but in lessions.php you're looking for it in session data.
$moduleID = $_SESSION['moduleID'];
Try:
$moduleID = isset($_GET['moduleID']) ? $_GET['moduleID'] : false;
if ( $moduleID ) {
$sql = sprintf('SELECT * FROM tblLessons WHERE moduleID = %d', $moduleID);
$result = #mysql_query($sql) or die(mysql_error());
} else {
// No moduleID, so show an error message, redirect user, or the like
}
Note that I'm using sprintf so that $moduleID is converted to a digit. The code you're using - passing the value directly to MySQL - is dangerous. Google: "sql injection".
If $moduleID can in fact be a string, then you need to take extra steps to ensure that the data is sanitized before being passed to MySQL, e.g.
$moduleID = isset($_GET['moduleID']) ? $_GET['moduleID'] : false;
if ( $moduleID ) {
$sql = sprintf("SELECT * FROM tblLessons WHERE moduleID = '%s'", mysql_real_escape_string($moduleID));
$result = #mysql_query($sql) or die(mysql_error());
} else {
// No moduleID, so show an error message, redirect user, or the like
}
You should also consider switching to PDO, as the mysql_ functions are depreciated. PDO is a much easier, safer way to interact with MySQL.

error: Notice: Undefined offset: 1 in C:\wamp\www\project\php\deleteRow.php on line 55

I got this error when trying to delete emails from a table form and database,,i tried to solved it but some fields work while others still gives me an error, any help is apreciated,,i am learning php on my own.
/here is my code/
<?php
$dbhost = 'host';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'databe_name';
$dbtable = 'database_table';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
//
mysql_select_db($dbname,$conn) or die ("Could not open database");
//
$sql="SELECT * FROM '$dbtable'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Sender</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Message</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Date</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows[0]; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows[2]; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows[3]; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows[4]; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if(isset($_POST['delete'])){
for($i=0;$i<$count;$i++){
$del_id = $_POST['checkbox'][$i]; /*this line gives me an error*/
$sql = "DELETE FROM '$dbtable' WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "<meta http-equiv='refresh' content='0' URL='deleteRow.php'>";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
Try:
if(isset($_POST['delete'])){
$checkboxCount = count($_POST['checkbox']);
for($i=0;$i<$checkboxCount;$i++){
$del_id = $_POST['checkbox'][$i];
$sql = "DELETE FROM '$dbtable' WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "";
}
}
Unchecked checkboxes do not have their value sent.
You probably need to replace your for body with:
if(isSet($_POST['checkbox'][$i])) {
$del_id = $_POST['checkbox'][$i]; /*this line gives me an error*/
$sql = "DELETE FROM '$dbtable' WHERE id='$del_id'";
$result = mysql_query($sql);
}
checkbox post fields are only available in the post when checked. so your post array can contain only values 1 and 2. you loop through all your db rows change your $count variable in the count of the checkbox array
$_POST['checkbox'][1] does not exist.
instead of using $count which is the number of query results in your code, use count($_POST['checkbox'])
So for($i=0;$i<$count;$i++){ would become
for($i=0; $i < count($_POST['checkbox']); $i++){
And on a second look, like others have suggested, not all indices of the checkbox may be set. It is better to use a foreach loop where you can get the key and value easily.
foreach($_POST['checkbox'] as $key => $value){
When a checkbox is not checked it won't show up in $_POST['checkbox'].
What you can do is to save all checked boxes in an array and after the loop execute a single delete query for all checked boxes.
for($i=0;$i<$count;$i++){
if (isset($_POST['checkbox'][$i])) $delids[] = $_POST['checkbox'][$i];
}
if (isset($delids) && is_array($delids)) {
$sql = "DELETE FROM '$dbtable' WHERE id IN (".implode(',', $delids).")";
$result = mysql_query($sql);
}
But a better way would be to skip your for-loop and use foreach instead like this:
foreach($_POST['checkbox'] as $c) {
$delids[] = $c;
}
if (isset($delids) && is_array($delids)) {
$sql = "DELETE FROM '$dbtable' WHERE id IN (".implode(',', $delids).")";
$result = mysql_query($sql);
}
I think the confusion lies in the fact that you're using the value ($count - the number of rows) to index into the value for each checkbox. The number of rows defines how many checkboxes there will be, but not the value of each checkbox. Hence $i in the delete loop is not guaranteed to be less than the size of the checkbox array.

Categories