Skip to content

Instantly share code, notes, and snippets.

@arkenidar
Last active October 24, 2017 18:59
Show Gist options
  • Save arkenidar/77b88861dd926c8cf4d2b0db8245ec74 to your computer and use it in GitHub Desktop.
Save arkenidar/77b88861dd926c8cf4d2b0db8245ec74 to your computer and use it in GitHub Desktop.
a simple PHP CRUD example. BTW I suggest to use Visual Studio Code + XDebug for coding and debugging.
<!doctype html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
</head>
<body>
<form method="post">
<input name="name" placeholder="name">
<input name="cost" placeholder="cost">
<input type="submit">
</form>
<?php
try {
$dbh = new PDO('sqlite:items.sqlite');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("create table if not exists items(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, cost FLOAT)");
$stmt->execute();
if(!empty($_REQUEST['name'])){
echo 'subimitted item<br>';
$stmt = $dbh->prepare("select sum(cost) from items where name=?");
$stmt->execute([$_REQUEST['name']]);
$rows = $stmt->fetchAll();
$cost = floatval($_REQUEST['cost']);
if($rows[0][0]==null){
$stmt = $dbh->prepare("insert into items(name,cost) values(?,?)");
$stmt->execute([$_REQUEST['name'], $cost]);
}else{
$new_cost = $cost + $rows[0][0];
if($new_cost != 0.0){
echo 'update<br>';
$stmt = $dbh->prepare("update items set cost=? where name=?");
$stmt->execute([$new_cost, $_REQUEST['name']]);
}else{
echo 'delete<br>';
$stmt = $dbh->prepare("delete from items where name=?");
$stmt->execute([$_REQUEST['name']]);
}
}
}else{
echo 'empty fields.<br>';
}
$stmt = $dbh->prepare("select * from items");
$stmt->execute();
?>
<table border="1">
<tr><td>name</td> <td>cost</td></tr>
<?php
foreach($stmt->fetchAll() as $row){
echo '<tr><td>'.$row['name'].'</td><td>'.$row['cost'].'</td></tr>';
}
?>
</table>
<?php
}
catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment