|
[back]
Deleting Records
Deleting records are done pretty much the same way as updating fields.
To delete a record, we need to know the ID number and we need a form to
pass this on to the PHP delete page.
<?php
$username="Yourusername";
$password="yourpassword";
$database="yourdatabase";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM students";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
echo "<p>"
?>
<table width=600 border=1>
<tr>
<th width=50>record ID</th>
<th width=250>first name</th>
<th width=250>last name</th>
<th width=50>grad year</th>
<th width=100>student number</th>
</tr>
<?php
$i=0;
while ($i < $num) {$id=mysql_result($result,$i,"id");
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$grad_year=mysql_result($result,$i,"grad_year");
$student_no=mysql_result($result,$i,"student_no");
?>
<tr>
<td><? echo "$id"; ?></td>
<td><? echo "$first"; ?></td>
<td><? echo "$last"; ?></td>
<td><? echo "$grad_year"; ?></td>
<td><? echo "$student_no"; ?></td>
</tr>
<?php
++$i;
}
echo "</table>";
?>
<!-- FIRST FORM TO UPDATE RECORD -->
<form action=update2.php method="post">
select the id number of the record you want to update: <input type=text
name="id">
<input type=submit>
</form>
<br>
<br>
<!-- ADD SECOND FORM TO DELETE RECORD -->
<form action=delete.php method="post">
select the id number of the record you want to delete: <input type=text
name="id">
<input type=submit>
</form>
Explanation:
Again, this is the same script we used for updating a field. The only
new part is the second form which will pass the ID number to the delete.php
page.
Part 2: CREATE PHP CODE THAT WILL DELETE THE RECORD - save as 'delete.php'
<?php
$username="mills";
$password="123";
$database="class";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$id=$_POST['id'];
$first=$_POST['first'];
$last=$_POST['last'];
$grad_year=$_POST['grad_year'];
$student_no=$_POST['student_no'];
$query="DELETE FROM students WHERE id='$id'";
mysql_query($query);
echo "Record Deleted";
mysql_close();
?>
<p>
<a href="update1.php">return to update page</a>
Explanation:
All we did here was to change the $query variable to DELETE and provide
a confirmation that the action was completed.
|