Skip to content

Instantly share code, notes, and snippets.

@deuterium7
Last active August 14, 2017 10:28
Show Gist options
  • Save deuterium7/a11460a9013543e3b8b14d6c3cb98359 to your computer and use it in GitHub Desktop.
Save deuterium7/a11460a9013543e3b8b14d6c3cb98359 to your computer and use it in GitHub Desktop.
Zabornyi Alex

admin.php

<?php
	ini_set('display_errors', 1);

	include('Session.php');
	include('Database.php');
	include('News.php');
	include('Categories.php');

	$session = new Session();

	if ( $session->getValue('admin') == true ) {
		$news = new News();
		$category = new Categories();

		$allNews = $news->getAll();
		echo "<a href='index.php'>Главная</a><br><h1>Новости</h1>";
		echo "<table><tbody><tr><th>id</th><th>categoty</th><th>title</th><th>body</th><th>date</th><th>update</th><th>delete</th></tr>";
		foreach ($allNews as $key => $options) {
			echo "<tr><td>".$options['id']."</td>";
			echo "<td>".$category->getCategoryName($options['category_id'])."</td>";

			if ( mb_strlen($options['title']) > 100 ) {
				$str = mb_substr($options['title'], 0, 100);
				echo "<td>".$str."...</td>";
			} else {
				echo "<td>".$options['title']."</td>";
			}

			if ( mb_strlen($options['body']) > 100 ) {
				$str = mb_substr($options['body'], 0, 100);
				echo "<td>".$str."...</td>";
			} else {
				echo "<td>".$options['body']."</td>";
			}
			echo "<td>".$options['date']."</td>";
			?>
			<td><a href='edit.php?id=<?=$options['id']?>'>Обновить</a></td>
			<td><a href='delete.php?id=<?=$options['id']?>'>Удалить</a></td>
			<?php
			echo "</tr>";
		}
		echo "</tbody></table><a href='edit.php' style='float:left;'>Добавить</a><a href='delete.php' style='float:right;'>Удалить все записи</a><br>";

		$allCategories = $category->getAll();
		echo "<h1>Категории</h1>";
		echo "<table><tbody><tr><th>id</th><th>name</th></tr>";
		foreach ($allCategories as $key => $options) {
			echo "<tr><td>".$options['id']."</td>";
			echo "<td>".$options['name']."</td>";
			?>
			<td><a href='edit2.php?id=<?=$options['id']?>'>Обновить</a></td>
			<td><a href='delete2.php?id=<?=$options['id']?>'>Удалить</a></td>
			<?php
			echo "</tr>";
		}
		echo "</tbody></table><a href='edit2.php'>Добавить</a><a href='delete2.php' style='padding-left:15px;'>Удалить все записи</a>";
	} else {
		header('Location: login.php');
	}
?>

Categories.php

<?php
	class Categories extends Database
	{
		public function __construct() {
			$this->tableName = 'categories';
			parent::__construct();
		}

		public function getCategoryName($id) {
			$stmt = parent::getOne($id);
			$name = $stmt[0]['name'];

			if ( isset($name) && !empty($name) ) {
				return $name;
			} else {
				return false;
			}
		}
	}
?>

Database.php

<?php
	class Database
	{
		// CONFIGS DEFAULT
		private $host = 'localhost';
		private $db = 'blog';
		private $user = 'root';
		private $password = 'root';
		private $charset = 'utf8';
		private $options = [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
		];

		// CONFIGS OTHER
		private $dsn;
		public $pdo;
		public $tableName;

		// METHODS
		public function __construct() {
            $this->dsn = "mysql:host=$this->host;dbname=$this->db;charset=$this->charset";
            $this->pdo = new PDO($this->dsn, $this->user, $this->password, $this->options);
		}

		public function getDsn() {
            return $this->dsn;
		}

		public function getAll() {
            $stmt = $this->pdo->query("SELECT * FROM $this->tableName");
            return $stmt->fetchAll();
		}

		public function getOne($id) {
            $stmt = $this->pdo->query("SELECT * FROM $this->tableName WHERE id = $id");
            return $stmt->fetchAll();
		}

		public function deleteAll() {
            $this->pdo->query("DELETE FROM $this->tableName");
		}

		public function deleteOne($id) {
            $this->pdo->query("DELETE FROM $this->tableName WHERE id = $id");	
		}

		public function updateOne($fieldArray, $fieldValue) {
            $strField = implode(" = ? ,",$fieldArray)." = ?";
            $sql = "UPDATE $this->tableName SET $strField WHERE id = ?";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($fieldValue);
            return $stmt;
		}

		public function insert($fieldArray, $fieldValue) {
            $strField = implode(" = ? ,",$fieldArray)." = ?";
            $sql = "INSERT INTO $this->tableName SET $strField";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($fieldValue);
            return $stmt;
		}
	}
?>

delete.php

<?php
	ini_set('display_errors', 1);

	include('Session.php');
	include('Database.php');
	include('News.php');

	$session = new Session();

	if ( $session->getValue('admin') == true ) {
		$news = new News();

		if ( isset($_GET['id']) && !empty($_GET['id']) ) {
			$news->deleteOne($_GET['id']);
		} else {
			$news->deleteAll();
		}

		header("Location: admin.php");
	} else {
		header('Location: login.php');
	}
?>

delete2.php

<?php
	ini_set('display_errors', 1);

	include('Session.php');
	include('Database.php');
	include('Categories.php');

	$session = new Session();

	if ( $session->getValue('admin') == true ) {
		$category = new Categories();

		if ( isset($_GET['id']) && !empty($_GET['id']) ) {
			$category->deleteOne($_GET['id']);
		} else {
			$category->deleteAll();
		}

		header("Location: admin.php");
	} else {
		header('Location: login.php');
	}
?>

edit.php

<?php
	ini_set('display_errors', 1);

	include('Session.php');
	include('Database.php');
	include('News.php');

	$session = new Session();

	if ( $session->getValue('admin') == true ) {
        $news = new News();

        if ( isset($_GET['id']) && !empty($_GET['id']) ) {
            $oneNews = $news->getOne($_GET['id']);

            if ( isset($_POST) && !empty($_POST) ) {
                $category_id = $_POST['category_id'];
                $title = $_POST['title'];
                $body = $_POST['body'];
                $date = $_POST['date'];
                $news->updateOne(["category_id","title","body","date"],[$category_id,$title,$body,$date,$_GET['id']]);
                header("Location: admin.php");
            }	
        } else {

            if ( isset($_POST) && !empty($_POST) ) {
                $category_id = $_POST['category_id'];
                $title = $_POST['title'];
                $body = $_POST['body'];
                $date = $_POST['date'];
                $news->insert(["category_id","title","body","date"],[$category_id,$title,$body,$date]);
                header("Location: admin.php");
            }
        }
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>Обновление новостей</title>
            <link rel="stylesheet" type="text/css" href="style.css">
        </head>
        <body>
            <form action="" method="post" class="center middle">
                <p><input type="text" name="category_id" value="<?=(isset($oneNews))?$oneNews[0]['category_id']:''?>" required> category_id</p>
                <p><input type="text" name="title" value="<?=(isset($oneNews))?$oneNews[0]['title']:''?>" required> title</p>
                <p><textarea rows="10" cols="45" name="body" required><?=(isset($oneNews))?$oneNews[0]['body']:''?></textarea></p>
                <p><input type="text" name="date" value="<?=(isset($oneNews))?$oneNews[0]['date']:''?>"> date (yyyy-mm-dd hh:mm:ss)</p>
                <p><input type="submit"></p>
            </form>
        </body>
        </html>
        <?php
	} else {
        header('Location: login.php');
	}
?>

edit2.php

<?php
	ini_set('display_errors', 1);

	include('Session.php');
	include('Database.php');
	include('Categories.php');

	$session = new Session();

	if ( $session->getValue('admin') == true ) {
        $category = new Categories();

        if ( isset($_GET['id']) && !empty($_GET['id']) ) {
            $oneCategory = $category->getOne($_GET['id']);

            if ( isset($_POST) && !empty($_POST) ) {
                $name = $_POST['name'];
                $category->updateOne(["name"],[$name,$_GET['id']]);
                header("Location: admin.php");
            }	
        } else {

            if ( isset($_POST) && !empty($_POST) ) {
                $name = $_POST['name'];
                $category->insert(["name"],[$name]);
                header("Location: admin.php");
            }
        }
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>Обновление новостей</title>
            <link rel="stylesheet" type="text/css" href="style.css">
        </head>
        <body>
            <form action="" method="post" class="center middle">
                <p><input type="text" name="name" value="<?=(isset($oneCategory))?$oneCategory[0]['name']:''?>" required> name</p>
                <p><input type="submit"></p>
            </form>
        </body>
        </html>
        <?php
	} else {
        header('Location: login.php');
	}
?>

index.php

<?php
	ini_set('display_errors', 1);

	include('Database.php');
	include('News.php');
	include('Categories.php');

	$news = new News();
	$category = new Categories();

	$allNews = $news->getAll();
	echo "<div class='center big'><h1>Список новостей</h1><br>";
	foreach ($allNews as $key => $options) {
		echo "<strong>".$category->getCategoryName($options['category_id'])." > ";
		echo $options['title']."</strong><br>";

		if ( mb_strlen($options['body']) > 400 ) {
			$str = mb_substr($options['body'], 0, 400);
			echo $str."...<br>";
		} else {
			echo $options['body']."<br>";
		}
		echo "<span class='left'>".$options['date']."</span>";
		?>
		<a class="right" href="post.php?id=<?=$options['id']?>">Читать далее</a>
		<?php
		echo "<br><hr>";
	}
	echo "<br><br><a href='login.php'>Войти в админку</a></div>";
?>

<!DOCTYPE html>
<html>
<head>
	<title>Страница новостей</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
</body>
</html>

login.php

<?php
	ini_set('display_errors', 1);
	include('Session.php');

	$session = new Session();

	if ( isset($_POST) && !empty($_POST) ) {

		$defaultLogin = 'admin';
		$defaultPassword = 'admin';
		if ( $_POST['login'] == $defaultLogin && $_POST['password'] == $defaultPassword ) {
			
			if ( $session->getValue('admin') ) {
				$session->updateValue('admin', true);
			} else {
				$session->saveValue('admin', true);
			}
			
			header('Location: admin.php');
		} else {
			$session->destroySession();
		}
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Форма авторизации</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<form action="" method="post" class="center small">
		<p><input type="text" name="login" required> login</p>
		<p><input type="password" name="password" required> password</p>
		<p><input type="submit" value="Войти"></p>
	</form>
</body>
</html>

News.php

<?php
	class News extends Database
	{
		public function __construct() {
			$this->tableName = 'news';
			parent::__construct();
		}
	}
?>

post.php

<?php
	ini_set('display_errors', 1);

	include('Database.php');
	include('News.php');

	$news = new News();

	$oneNews = $news->getOne($_GET['id']);
	echo "<div class='center big'>";
	echo "<h2>".$oneNews[0]['title']."</h2><br>";
	echo $oneNews[0]['body']."<br>";
	echo "<span class='left'>".$oneNews[0]['date']."</span>";
	echo "<a class='right' href='index.php'>Назад</a>";
	echo "</div>";
?>

<!DOCTYPE html>
<html>
<head>
	<title>Новость</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
</body>
</html>

Session.php

<?php
	class Session
	{
		public function __construct() {
			session_start();
		}

		public function saveValue($key, $value) {

			if ( !isset($_SESSION[$key]) ) {
				$_SESSION[$key] = $value;	
			}
		}

		public function deleteValue($key) {

			if ( isset($_SESSION[$key]) ) {
				unset($_SESSION[$key]);
			}
		}

		public function updateValue($key, $value) {

			if ( isset($_SESSION[$key]) ) {
				$_SESSION[$key] = $value;	
			}
		}

		public function getValue($key) {

			if ( isset($_SESSION[$key]) ) {
				return $_SESSION[$key];
			} else {
				return false;
			}
		}

		public function destroySession() {
			
			if ( isset($_SESSION) ) {
				session_destroy();
			}
		}
	}
?>

style.css

* { margin: 0; padding: 0; }
p { padding: 10px 10px; }
h2 { text-align: center; }
.center { margin: 0 auto; text-align: justify; }
.small { width: 400px; }
.middle { width: 600px; }
.big { width: 900px; }
.left { float: left; }
.right { float: right; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment