CRUD application example

A classical form of the web database interface often called CRUD - after Create, Read, Update and Delete.
These 4 operations are like basic musical scales - lets you build any application out of these bricks.
Here is an example of such a basic application which performs listing (R), adding(C), editing(U) and deleting records.

With SafeMySQL clas it's going to be literally a few lines. And it can be easily extended to whatever number of fields, without writing additional code, but only by extending form template and adding new members to the $fields variable.

include 'safemysql.class.php';
$db    = new SafeMysql();
$table "test"

  if (isset(
$_POST['delete'])) {
$db->query("DELETE FROM ?n WHERE id=?i"$table$_POST['delete']);
  } elseif (
$_POST['id']) { 
$db->query("UPDATE ?n SET name=?s WHERE id=?i",$table$_POST['name'], $_POST['id']);
  } else { 
$db->query("INSERT INTO ?n SET name=?s"$table$_POST['name']);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);  
if (!isset(
$_GET['id'])) {
$LIST $db->getAll("SELECT * FROM ?n",$table);
} else {
  if (
$_GET['id']) {
$row $db->getRow("SELECT * FROM ?n WHERE id=?i"$table$_GET['id']);
    foreach (
$row as $k => $v$row[$k]=htmlspecialchars($v); 
  } else { 

Also we well need 2 templates,
<a href="?id=0">Add item</a>
<?php foreach ($LIST as $row): ?>
<li><a href="?id=<?=$row['id']?>"><?=$row['name']?></a>
<? endforeach ?>

...and form.php:
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
<a href="?">Return to the list</a>
<?php  if ($row['id']):?>
<div align=right>
<form method="POST">
<input type="hidden" name="delete" value="<?=$row['id']?>">
<input type="submit" value="delete"><br>
<?php endif?>

Related articles: