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.
<?php
include 'safemysql.class.php';
$db = new SafeMysql();
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') {
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']);
exit;
}
if (!isset($_GET['id'])) {
$LIST = $db->getAll("SELECT * FROM ?n",$table);
include 'list.php';
} 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 {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
Also we well need 2 templates,
list.php
<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>
</form>
<?php if ($row['id']):?>
<div align=right>
<form method="POST">
<input type="hidden" name="delete" value="<?=$row['id']?>">
<input type="submit" value="delete"><br>
</form>
</div>
<?php endif?>
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote