Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.02 KB | None | 0 0
  1. <?php
  2. class simpleCMS { //работа с БД
  3.     public $host = "localhost"; //параметр класа
  4.     public $username = "root";
  5.     public $password = "";
  6.     public $db = 'testDB';
  7.    
  8.  
  9.     public function connectDB() { //функция подключения к серверу MySQL
  10.         $link = mysql_connect($this->host, $this->username, $this->password); //подключаемся к серверу MySQL
  11.         if (!$link) { //проверяем произошло ли подключение к серверу
  12.             die('Ошибка соединения: ' . mysql_error()); //false, функция вывода ошибки
  13.         } // закрытие условия if
  14.         mysql_select_db($this->db) or die("Не могу найти БД. " . mysql_error()); //подсоеденяем БД
  15.             $this->buildDB(); //вызываем функцию создания таблицы
  16.         return $link; //вовзращение переменной с содержанием функции подключения к серверу
  17.     } //закрытие функции подключения к серверу
  18.    
  19.     public function buildDB() { //функция создания таблицы 20//переменной задаем значение создания таблицы "messages" c 'полями' их типом и макс длинной строки
  20.         $sql = "CREATE TABLE IF NOT EXISTS `messages` (
  21.  `mid` int(11) NOT NULL AUTO_INCREMENT,
  22.  `title` varchar(150) DEFAULT NULL,
  23.  `body` text,
  24.  `created` varchar(100) DEFAULT NULL,
  25.  `contacts` varchar(13) NOT NULL,
  26.  PRIMARY KEY (`mid`)
  27. ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ";
  28.           $result =  mysql_query($sql);
  29.           return $result;
  30.     }
  31.    
  32.     public function write($p) { //функция записи сообщения
  33.         $sql = 'INSERT INTO messages(title, body, created, contacts) VALUES("' . $p["title"] . '" , "' . $p["body"] . '", ' . time() .', "'.$p["contacts"].'")';  //оператор(колонки) значения (к каждой колонке)
  34.         return mysql_query($sql) or die(mysql_error());
  35.     }
  36.    
  37.     public function display_public() { //функция вывода сообщений
  38.         $content = '';
  39.         $sql = 'SELECT * FROM messages ORDER BY mid DESC'; // оператор запроса выборки * - выбор всех полей  каждой строки из "messages" таблицы
  40.         $result = mysql_query($sql) or die(mysql_error()); //выполнение запроса выборки
  41.          
  42.         while($row = mysql_fetch_array($result)) {
  43.             $content .='<table class="post" style="border: 2px solid #cccccc;
  44.             border-collapse: separate;
  45.             border-spacing: 10px;
  46.             padding: 5px;">';// оборачивает запись
  47.             $content .='<tr>';
  48.             $content .= '<td><span class="time">#' . $row['mid'] . '</td><td>от' .date('d-m-Y', $row['created']) . '</span></td><td><h2>' . $row['title'] . '</h2></td>'; //вывод времени и заголовка
  49.             $content .= '<td><p>' . $row['body']. '</p></td>'; //вывод текста
  50.             $content .= '<td><p>' . $row['contacts']. '</p></td><br>'; //вывод контактов
  51.             $content .='</tr>';
  52.             $content .= '<tr><td><p><a href="/index.php?admin=update&mid='.$row['mid'].'">Редактировать сообщение</a></p></td></tr>';
  53.             $content .= '</table>'; //закрывающая запись
  54.         }
  55.         $content .= '<p><a href="/index.php?admin=add"> Добавить сообщение</a></p>'; //ссылка на добавление сообщения
  56.         return $content;
  57.     }
  58.    
  59.     public function update($p) {
  60.          $sql = 'UPDATE `messages` SET  `title` = "' . $p["title"] . '", `body` = "' . $p["body"] . '", `created` =  "' . $p["created"] .'" , `contacts` = "'.$p["contacts"].'" WHERE `messages`.`mid` = "'.$p['mid'].'" ';
  61.          mysql_query($sql) or die(mysql_error());
  62.     }
  63.    
  64.     public function post_update() {
  65.          $message_id = $_POST['mid'];
  66.          if(!empty($message_id)){
  67.             $result = mysql_query('SELECT * FROM messages WHERE mid='.$message_id) or die(mysql_error() );
  68.             $row = mysql_fetch_object($result);
  69.             $form = <<<HTML
  70.             <form action="/index.php?admin=update" method="post">
  71.             <label for="title">Имя:</label><br>
  72.             <input type="text" id="title" name="title" maxlength="150" value=$row->title><br>
  73.             <input type="hidden" name="mid" id="mid" value=$row->mid ><br>
  74.             <label for="body">Сообщение:</label><br>
  75.             <textarea name="body" id="body"> $row->body </textarea><br>
  76.             <input type="submit" value="Сохранить">
  77.             </form>
  78.             <p><a href="/index.php">Вернуться на главную</a></p>
  79. HTML;
  80.         }else{
  81.             if (!empty($_POST)) {
  82.             $p = array(  "mid" => $_POST['mid'], "title" => $_POST["title"], "body" => $_POST["body"], "created" => time(), "contacts" => $_POST["contacts"] );
  83.             $this->update($p);
  84.             $form .= '<p>Сообщение изменено!';
  85.             $form .= '<p><a href="/index.php#mid-'.$_POST['mid'].'">Перейти к записи</a></p>';
  86.         }else{
  87.             $form .=   '<p>Нет значения mid!</p>';
  88.             $form .= '<p><a href="/index.php">Вернуться на главную</a></p>';
  89.         }
  90.     }
  91.   return $form;
  92. }
  93.  
  94.    
  95. }
  96.  
  97. $obj = new simpleCMS; //создание обьекта класа
  98. $db_connection = $obj->connectDB(); //назначение переменной вызова функции подключения к серверу  (к БД)
  99. $item = array("title" => "заголовок", "body" => "текст", "contacts" => "номер"); //назначение переменной функции массива с (ключами-названий поля и => их значений)
  100. echo $obj->write($item); //вызов функци записи сообщений через массива
  101. //$p = array( "mid" =>"2", "title" => "привет котя", "body" => "как дела?", "created" => time(), "contacts" => "номер");
  102. //echo $obj->update($p);
  103. echo $obj->post_update();
  104. echo $obj->display_public();
  105. mysql_close($db_connection); // закрытие подсоеденения к БД
  106. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement