Create A Message Board Using PHP – PHP App

Control Over User Login Procedure - Cookies Authentication
Control Over User Login Procedure - Cookies Authentication

आज इस आर्टिकल में हम आपको Create A Message Board Using PHP – PHP App के बारे में बताएंगे।

Problem:- Create A Message Board Using PHP – PHP App

Solution:-

First of all Make a table in your database here i using testdb as database name and message as table name

Creating Table using SQL Query

CREATE TABLE message(
    id INTEGER PRIMARY KEY AUTO_INCREAMENT NOT NULL,
    posted_on DATETIME NOT NULL,
    author CHAR(255),
    subject CHAR(255),
    body MEDIUMTEXT,
    thread_id INT UNSIGNED NOT NULL,
    parent_id INT UNSIGNED NOT NULL,
    level INT UNSIGNED NOT NULL,
    thread_pos INT UNSIGNED NOT NULL
);

message.php

<?php 

//creating a object of messageBoard class
$board = new MessageBoard();
// calling a method inside messageBoard class
$board->go();

class MessageBoard{
	protected $db;
	protected $form_errors = array();
	protected $inTransaction = false;
        
// setting up the databse connection
	public function __construct(){
		set_exception_handler(array($this, 'logAndDie'));
		$this->db = new PDO("mysql:host=localhost; dbname=testdb", 'root', '');
		$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}
// using superglobal variable we use single page to display all message with view, submit, and save 
	public function go(){
		$cmd = isset($_REQUEST['cmd'])? $_REQUEST['cmd'] : "show";
		switch ($cmd) {
			case 'read':
				$this->read();
				break;
			case 'post':
				$this->post();
				break;
			case 'save':
				if ($this->valid()) {
					$this->save();
					$this->show();
				}else{
					$this->post();
				}
				break;
			case 'show':
			default:
				$this->show();
				break;
		}
	}
// to save and update messsage
	protected function save(){
		$parent_id = isset($_REQUEST['parent_id']) ? intval($_REQUEST['parent_id']) : 0;
		$this->db->beginTransaction();
		$this->inTransaction = true;

		if ($parent_id) {
			$st = $this->db->prepare("SELECT thread_id, level, thread_pos FROM message WHERE id = ?");
			$st->execute(array($parent_id));
			$parent = $st->fetch();

			$level = $parent['level'] + 1;

			$st = $this->db->prepare("SELECT MAX(thread_pos) FROM message WHERE thread_id = ? AND parent_id = ?");
			$st->execute(array($parent['thread_id'], $parent_id));
			$thread_pos = $st->fetchColumn(0);

			if ($thread_pos) {
				$thread_pos++;
			}else{
				$thread_pos = $parent['thread_pos'] + 1;
			}
			$st = $this->db->prepare("UPDATE message SET thread_pos = thread_pos + 1 WHERE thread_id = ? AND thread_pos >= ?");
			$st->execute(array($parent['thread_id'], $thread_pos));

			$thread_id = $parent['thread_id'];
		}else{
			$thread_id = $this->db->query("SELECT MAX(thread_id) + 1 FROM message")->fetchColumn(0);
			if (!$thread_id) {
				$thread_id = 1;
			}
			$level = 0;
			$thread_pos = 0;
		}
		$st = $this->db->prepare("INSERT INTO message (id, thread_id, parent_id, thread_pos, posted_on, level, author, subject, body) VALUES (?,?,?,?,?,?,?,?,?)");
		$st->execute(array(null, $thread_id, $parent_id, $thread_pos, date('c'), $level, $_REQUEST['author'], $_REQUEST['subject'], $_REQUEST['body']));

		$this->db->commit();
		$this->inTransaction = false;
	}

//to show all message 
	protected function show(){
		print "<h2>Message List</h2><p>";

		$st = $this->db->query("SELECT id, author, subject, LENGTH(body) AS body_length, posted_on, level FROM message ORDER BY thread_id, thread_pos");
		while($row = $st->fetch()){
			print str_repeat("&nbsp", 4*$row['level']);

			$when = date('Y-m-d h:i', strtotime($row['posted_on']));
			print "<a href='".htmlentities($_SERVER['PHP_SELF'])."?cmd=read&amp;id={$row['id']}'>".htmlentities($row['subject']).'</a> by'. htmlentities($row['author']). '@'.
			htmlentities($when). "({$row['body_length']} bytes)<br/>";
		}
		print "<hr/><a href='".htmlentities($_SERVER['PHP_SELF'])."?cmd=post'>Start Messaging</a>";

	}
// to read a single person message and reply them.
	public function read(){
		if (!$_REQUEST['id']) {
			throw new Exception("No Message ID Supplied");
		}
		$id = intval($_REQUEST['id']);
		$st = $this->db->prepare("SELECT author, subject, body, posted_on FROM message WHERE id = ?");
		$st->execute(array($id));
		$msg = $st->fetch();

		if (!$msg) {
			throw new Exception("Bad Request");
		}
		
		$body = nl2br(htmlentities($msg['body']));

		$self = htmlentities($_SERVER['PHP_SELF']);
		$subject = htmlentities($msg['subject']);
		$author = htmlentities($msg['author']);

		print "<h2>".$subject."</h2><h3>By ".$author."</h3><p>".$body."</p><hr/>";
		print "<a href='".$self."?cmd=post&parent_id=$id'>Reply</a><br><a href='".$self."?cmd=list'>List Message</a>";
	}
// for start messaging
	public function post(){
		$safe = array();
		foreach (array('author', 'subject', 'body') as $field) {
			if (isset($_POST[$field])) {
				$safe[$field] = htmlentities($_POST[$field]);
			}else{
				$safe[$field] = " ";
			}
			if (isset($this->form_errors[$field])) {
				   $this->form_errors[$field] = "<span style='color:red;'>". $this->form_errors[$field]. "</span>";              
				}else{
					$this->form_errors[$field] = " ";
				}
		}
		if (isset($_REQUEST['parent_id']) && $parent_id = intval($_REQUEST['parent_id'])) {
			$parent_field = sprintf('<input type="hidden" name="parent_id" value="%d">', $parent_id);
			if (!strlen($safe['subject'])) {
				$st = $this->db->prepare('SELECT subject FROM message WHERE id=?');
				$st->execute(array($parent_id));
				$parent_subject = $st->fetchColumn(0);
				$safe['subject'] = htmlentities($parent_subject);

				if ($parent_subject && (!preg_match('/^re:/i', $parent_subject))) {
					$safe['subject'] = "Re: {$safe['subject']}";
				}
			}
		}else{
				$parent_field = ' ';
			}
			$self = htmlentities($_SERVER['PHP_SELF']);
			print "<form method = 'post' action = '{$self}'><table border='2'><tr><td>Your Name</td><td>{$this->form_errors['author']}<input type='text' name='author' value='{$safe['author']}'></td></tr>";
			print "<tr><td>Subject</td><td>{$this->form_errors['subject']}<input type='text' name='subject' value='{$safe['subject']}'></td></tr>";
			print "<tr><td>Message:</td><td>{$this->form_errors['body']}<textarea rows='4' cols='30' name='body'>{$safe['body']}</textarea></td></tr>";
			print "<tr><td colspan='2'><input type='submit' value='Post Message'></td></tr></table>";
			print $parent_field;
			print "<input type='hidden' name='cmd' value='save' /></form>";

			}
// checking message box and return any error if something not found or not set
	public function valid(){
		$this->form_errors = array();
		if (!(isset($_POST['author']) && strlen(trim($_POST['author'])))) {
			$this->form_errors['author'] = "Please Enter Your Name";
		}

		if (!(isset($_POST['subject']) && strlen(trim($_POST['subject'])))) {
			$this->form_errors['subject'] = "Please Enter Your Message Subject";
		}

		if (!(isset($_POST['body']) && strlen(trim($_POST['body'])))) {
			$this->form_errors['body'] = "Please Write Your Message";
		}
		return (count($this->form_errors)==0);
	}
// to get error message of database...
	public function logAndDie(Exception $e){
		print 'Error: '.htmlentities($e->getMessage());
		if ($this->db && $this->db->inTransaction()) {
			$this->db->rollback();
		}
		exit();
	}
		}

 ?>

Final Words

  • आज इस आर्टिकल में हमने आपको CreateA Message Board Using PHP- PHP App के बारे में बताया।
  • अगर आपको इससे जुडी कोई अन्य जानकारी चाहए है तो निचे कमेन्ट बॉक्स में कमेन्ट कर के पूछ सकते है।

इसे भी पढ़े – Caching Queries & Result without Rerun Database

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *