forum.php
Jednoduché diskuzní fórum v PHP
php
<?php
class Model {
private $db = null;
private $attrib = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
private function getDB() {
if (!isset($this->db)) {
$this->db = new PDO('mysql:dbname=test;host=localhost', '', '', $this->attrib);
}
return $this->db;
}
function createTableClanek($clanek) {
$this->getDB()->query("CREATE TABLE clanek (obsah text)");
}
function getSeznamClanku() {
return $this->getDB()->query("SELECT * FROM clanek")->fetchAll(PDO::FETCH_ASSOC);
}
function insertClanek($clanek) {
if (empty($clanek)) {
throw new Exception("Textové pole nebylo vyplněno.");
}
$prep=$this->getDB()->prepare("INSERT INTO clanek VALUES (?)");
$prep->execute(array($clanek));
}
}
class MySession {
function setMessage($message) {
$_SESSION['message'] = $message;
}
function __toString() {
if (isset($_SESSION['message']))
return "<h2>".$_SESSION['message']."</h2>";
return "";
}
}
session_start();
$model = new Model();
$session = new MySession();
if (isset($_POST['clanek'])) {
try {
$model->insertClanek($_POST['clanek']);
$session->setMessage("Článek byl úspěšně uložen");
header('Location: .');
exit();
} catch (Exception $e) {
$session->setMessage($e->getMessage());
}
}
$pole=array();
try {
foreach ($model->getSeznamClanku() as $clanek) {
$pole[]="<tr><td>".htmlspecialchars($clanek['obsah'])."</td></tr>";
} catch (Exception $e) {
$pole[]="<tr><td>".htmlspecialchars($e->getMessage())."</td></tr>";
}
$seznam=implode("\n", $pole);
echo <<<EOT
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h1>Přidej článek</h1>
$session
<table>
$seznam
</table>
<form method="POST">
<table>
<tr><td><textarea rows="10" cols="150" name="clanek"></textarea></td></tr>
<tr><td><input type="submit" value="Odeslat"></td></tr>
</table>
</form>
</body>
</html>
EOT;
Neformátovaný
Přidáno: 19.7.2013
Expirace: Neuvedeno