- <?php
- class GuestBook {
- private $_pdo = null;
- public function __construct($host, $dbname, $username, $password){
- try{
- $this->_pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
- }catch(PDOException $e){
- throw new PDOException($e->getMessage(), $e->getCode(), $e);
- }
- }
- public function addComment($author, $subject, $comment){
- if ($this->_pdo){
- $stm = $this->_pdo->prepare("INSERT INTO guest_book (author,subject,comment,posted_date) VALUES (:author,:subject,:comment,NOW())");
- $stm->bindParam(':author', $author);
- $stm->bindParam(':subject', $subject);
- $stm->bindParam(':comment', $comment);
- if ($stm->execute()){
- return true;
- }
- }
- return false;
- }
- public function getComments(){
- if ($this->_pdo){
- $stm = $this->_pdo->prepare("SELECT * FROM guest_book");
- if ($stm->execute()){
- return $stm->fetchAll(PDO::FETCH_OBJ);
- }
- }
- return false;
- }
- public function getCommentById($comment_id){
- if ($this->_pdo){
- $stm = $this->_pdo->prepare("SELECT * FROM guest_book WHERE comment_id=$comment_id");
- if ($stm->execute()){
- return $stm->fetch(PDO::FETCH_OBJ);
- }
- }
- return false;
- }
- public function deleteCommentById($comment_id){
- if ($this->_pdo){
- $stm = $this->_pdo->prepare("DELETE FROM guest_book WHERE comment_id=$comment_id");
- if ($stm->execute()){
- return true;
- }
- }
- return false;
- }
- }
- // Example usage
- try{
- $book = new GuestBook('localhost', 'database', 'username', 'password');
- // Add a new comment
- $book->addComment('John Smith', 'Hello', 'This is a comment');
- // Get all comments
- $comments = $book->getComments();
- // Get comment by comment id
- $comment = $book->getCommentById(1);
- // Delete comment by comment id
- $book->deleteCommentById(2);
- }catch(PDOException $e){
- // Print error message
- echo $e->getMessage();
- }
- ?>
- //guest_book.sql
- DROP TABLE IF EXISTS guest_book;
- CREATE TABLE guest_book (
- comment_id int(11) NOT NULL AUTO_INCREMENT,
- author varchar(80) DEFAULT NULL,
- subject varchar(50) DEFAULT NULL,
- comment text NOT NULL,
- posted_date datetime NOT NULL,
- PRIMARY KEY (comment_id)
- )
PHP - Guestbook Class
This class can be used to setup a simple guestbook. The class allows you to add comments, get comments and delete comments. This example uses a database to store the comments.
1 comment:
Packers and Movers Bangalore @ http://www.buy5th.in/movers-and-packers-bangalore.html
Packers and Movers Hyderabad @ http://www.buy5th.in/movers-and-packers-hyderabad.html
Packers and Movers Delhi @ http://www.buy5th.in/movers-and-packers-delhi.html
Packers and Movers Pune @ http://www.buy5th.in/movers-and-packers-pune.html
Packers and Movers Ghaziabad @ http://www.buy5th.in/movers-and-packers-ghaziabad.html
Post a Comment