Log in

View Full Version : deleting records in php



ravi951
08-18-2011, 02:03 PM
hi all,
i have created one form for inserting and deletion.
my database name is "test" table name is "emp" which contains three fields
namely empno,empname,desig.
i have inserted some 4 to 5 values for the above table.
i have not made emp no as primary key.
i have entered random number for empno.and some values for empname and desig.
below is for insert is "new1.php"


<?php
function checkform($empno,$empname,$desig,$error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error!= '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>EmpNo: </strong> <input type="text" name="empno" value="<?php echo $empno; ?>" /><br/>
<strong>EmpName: </strong> <input type="text" name="empname" value="<?php echo $empname; ?>" /><br/>
<strong>Desig: </strong> <input type="text" name="desig" value="<?php echo $desig; ?>" /><br/>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
include('connect_db1.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$empno =mysql_real_escape_string($_POST['empno']);
$empname = mysql_real_escape_string($_POST['empname']);
$desig = mysql_real_escape_string($_POST['desig']);

if ($empno == '' || $empname == '' || $desig == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';

// if either field is blank, display the form again
checkform($empno,$empname,$desig,$error);
}
else
{
mysql_query("INSERT emp SET empno='$empno', empname='$empname',desig='$desig'")
or die(mysql_error());
header("Location: view1.php");
}
}
else
{
checkform('','','','');
}
?>

below is "connect_db1.php"


<?php
$connection = mysql_connect("localhost","root","")
or die ("Could not connect to server ... \n" . mysql_error());
mysql_select_db("test")
or die ("Could not connect to database ... \n" . mysql_error());
?>

i am unable to delete the records .
kindly tell me how to delete the records in my table.this is with out autoincrement.
below is my "delete1.php"


<?php
// connect to the database
include('connect_db1.php');
if (isset($_POST['empno'])) /*&& is_numeric($_POST['empno'])) */
{
$empno = $_POST['empno'];
$result = mysql_query("DELETE FROM emp WHERE empno=$empno")
or die(mysql_error());
header("Location:view1.php");
}
else
{
header("Location:view1.php");
}
?>

i have also have "view1.php"


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>

<?php
include('connect_db1.php');
$result = mysql_query("SELECT * FROM emp") or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>EmpNo</th> <th>EmpName</th> <th>Desig</th> <th></th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array($result))
{
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['empno'] . '</td>';
echo '<td>' . $row['empname'] . '</td>';
echo '<td>' . $row['desig'] . '</td>';
echo '<td><a href="delete1.php?empno=' . $row['empno'] . '">Delete</a></td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p><a href="new1.php">Add a new record</a></p>
</body>
</html>

please tell me how to delete the records........

JShor
08-18-2011, 09:16 PM
Because empno is a query string variable, and not a _POST variable. Try changing _POST to _GET here:



<?php
// connect to the database
include('connect_db1.php');
if (isset($_GET['empno'])) /*&& is_numeric($_POST['empno'])) */
{
$empno = $_GET['empno'];
$result = mysql_query("DELETE FROM emp WHERE empno=$empno")
or die(mysql_error());
header("Location:view1.php");
}
else
{
header("Location:view1.php");
}
?>

JShor
08-18-2011, 09:17 PM
I knew that because of this line:


echo '<td><a href="delete1.php?empno=' . $row['empno'] . '">Delete</a></td>';


Looks like your URL structure is delete1.php?empno={empty number}, indicating that you're passing variables via a query string.

traq
08-18-2011, 11:06 PM
of course, doing something like this would allow anyone who knew about it to delete any record, at will. and if you don't validate/escape $_GET['empno'], they could gain unrestricted access to your entire database.

JShor
08-19-2011, 12:59 AM
That too. I was too tired/oblivious to go over them. But you're completely right. I recommend using mysql_escape_string() to escape the deletion variable, and have a system that checks if the user who has access to the link also has access to delete it (and you would do this by adding an additional conditional within the conditional that checks whether $_GET['empno'] is set or not, and then run the SQL query if they have access to delete the record).

Another thing I would do is to put a confirm box that asks the user whether they really want to delete the record or not. Sometimes people are forgetful/absent-minded/too uncoordinated with the cursor, and may click the link by accident and POOF, the record is gone forever.

ravi951
08-19-2011, 05:29 AM
hi,
in the above program i have been using links for adding a new record and for deleting.
is it possible to use button with name as "submit" there.
whether we have to use javascript or with out javascript also can we do.
is it possible?
if possible kindly tell me.....

JShor
08-19-2011, 03:20 PM
Yes. Use the <button> HTML tag.

Example:


<button onclick="window.location.href = 'delete1.php?empno=4'">Delete</button>

traq
08-19-2011, 04:29 PM
you can do so without javascript as well by using a regular form:
<form action="delete1.php?empno=4">
<input type="submit" value="Delete">
</form>

however, this is really not the best approach. GET query strings are intended simply for telling the server something you want to see (like here on the forums, ?do=postreply&t=64112 tells the server that I want to see the "post reply" page and write a reply to this thread. the actual reply, however, will be send by POST).

for actions like this, that change things on the server, you should really be sending the command via POST, and not via the query string. Not accepting commands like this in the browser address bar is the first, and most critical, step in preventing your script from being an entry point for malicious users.


<form action="delete1.php" method="POST">
<input type="hidden" name="token" value="someRandomUniqueValue">
<!--you check this to ensure that it's _really_ your form-->
<input name="empno">
<!--this field will be where the user can specify what he wants to delete-->
<!--if _you_ want to specify, then make this a hidden field instead:
<input type="hidden" name="empno" value="4">
or, just store the desired empno in your SESSION and don't show it to the user at all
-->
<input type="submit" value="Delete">
</form>

Doing this will require changes to your script, but it is better to learn how now and do it with every form you build, especially if it's something critical/permanent. You might serve and check the form like this:
<?php session_start();
if(isset($_POST['empno'])){
// someone submitted the form, so we will validate it
// first, check the token (see below to find out how the token was set)
if($_POST['token'] !== $_SESSION['token']){ exit("Bad token!"); }
// next, check the empno to make sure it's valid (needs to be a number, right?)
elseif(!ctype_digit($_POST['empno'])){ exit("Bad empno!"); }
else{
$empno = $_POST['empno'];
/* go ahead and delete the record */
}
}else{
// there was no form submission, so we'll display the form
// first, set up the token that we'll check later.
// there are many possible ways to do this,
// it just needs to be some random value that is
// _hard_to_guess_ and is only used _once_.
$token = md5(time());
$form = '
<form action="delete1.php" method="POST">
<input type="hidden" name="token" value="'.$token.'">
<input name="empno">
<input type="submit" value="Delete">
</form>';
print $form;
?>
for something like this, that allows changes to your database, you'd probably want to make sure that the user is logged in first as well.

This (http://phpsec.org/projects/guide/2.html) is a good intro to form security.