Updating Records
If we can view, add and delete records in a database, the only thing left is to be able to edit information. Like with the deletion, we generally want the user to select the record they want to edit before giving them a form on which to perform the changes.
The whole script is shown below. Comments indicate the purpose of each section,
<?php
echo "<h1>Editing Stuff</h1>";
// database connection
$h = "localhost";
$u = "root";
$p = "";
$connection = mysql_connect($h,$u,$p);
if (!$connection)
{
die("Could not connect to the database");
}
mysql_select_db("test");
if (isset($_POST['toedit']))
{
// user has chosen to edit, show them a form for this
$change= $_POST['toedit'];
$query = "SELECT * FROM person WHERE personid=".$change;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
extract($row);
echo "<form action='update.php' method='POST'><input type='hidden' name='toupdate' value='".$personid."'>\n";
echo "<table><tr><td>Surname:</td><td><input type='text' name='sname' maxlength='25' value='".$surname."'></td>";
echo "</tr><tr><td>Forename:</td><td><input type='text' name='fname' maxlength='25' value ='".$forename."'></td>";
echo "</tr><tr><td>Description:</td><td><textarea name='desc' maxlength='255'>".$description."</textarea></td>";
echo "</tr>
<tr>
<td><input type='reset' value='Reset Form'></td><td><input type='submit' value='Save Changes'></td>
</tr>
</table>
</form>";
}
elseif (isset($_POST['toupdate']))
{
// user has edited the form and chosen to save changes
$change = $_POST['toupdate'];
$fsurname = $_POST['sname'];
$fforename = $_POST['fname'];
$fdescription = $_POST['desc'];
// VALIDATE at this point
$query = "UPDATE person SET surname='".$fsurname."', forename='".$fforename."', description='".$fdescription."' WHERE personid=".$change;
$result = mysql_query($query);
echo "<p>Changes Made. <a href='update.php'>Do some more</a>.</p>";
}
else
{
// display all records
$query = "SELECT * FROM person";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num>0)
{
echo "<table><tr><th>Person Id</th><th>Surname</th><th>Forename</th><th>Description</th><th> </th></tr>\n";
while ($row = mysql_fetch_array($result))
{
extract($row);
echo "<tr><td>".$personid."</td><td>".$surname."</td><td>".$forename."</td><td>".$description."</td><td>\n";
echo "<form action='update.php' method='POST'><input type='hidden' name='toedit' value='".$personid."'>
<input type='submit' value='EDIT'></form>\n
</td></tr>";
}
echo "</table>";
}
else
{
echo "<p>No records in the table.</p>";
}
}
Like when you add a record, you need to perform validation before submitting the query. If you get your validation right, there is no reason to expect database errors.