Return to Snippet

Revision: 67066
at August 6, 2014 19:25 by dmkim


Initial Code
define ('EPP',3);
 
check_base();
 
   if (isset($_POST['submit']))
      save_vals();
 
show_entries();
 
 
show_form();
 
function check_base() {
   global $db;
   error_reporting(E_ERROR);
   $db = new mysqli('','','','');
   error_reporting(E_ALL);
   if (mysqli_connect_errno())
      throw new Exception ('connect error: '.mysqli_connect_error());
 
   $rez = $db->query ("show tables like 'gbookz'");
 
   if ($rez->num_rows==0) {
      $db->query('create table gbookz (id int(11) not null auto_increment,'.
           'username varchar(20), message varchar(200), pubdate datetime, '.
           ' primary key(`id`))');
 
      if ($db->errno!=0) {
          echo $db->error;
          exit();
         }
 
 
    echo 'created gbookz table<br/>';
   }
   $rez->free();
 
}
 
function save_vals() {
 
   global $db;
 
   $stmt = $db->prepare('insert into gbookz(username,message,pubdate) '.
            'values(?,?,?)');
 
   $stmt->bind_param('sss', $_POST['username'], $_POST['message'],
      date('Y-m-d H:i:s'));
 
   $stmt->execute();
 
   if ($stmt->errno!=0) {
      throw new Exception ('db error: '.$stmt->error);
   }
 
   echo 'record saved with id='.$stmt->insert_id.'<br/>';
}
 
function show_entries() {
 
   global $db;
 
   $page = (isset($_GET['page'])) ? $_GET['page'] : 1;
 
   $rez = $db->query('select count(*) from gbookz');
 
   $num_rows = $rez->fetch_array(MYSQLI_NUM);
   $pages = ceil($num_rows[0]/EPP);
 
   $rez->free();
 
   ob_start();
   for ($i=0; $i<$pages; $i++) {
      echo str_repeat('&nbsp',3);
      if ($i+1==$page)
         echo ($i+1);
      else
         echo '<a href="'.$_SERVER['PHP_SELF'].'?page='.($i+1).'">'.($i+1).'</a>';
 
      if (($i+1)%10==0)
         echo '<br/>';
   }
   $nav = ob_get_clean();
 
 
   $stmt = $db->prepare('select id,username,message,pubdate from gbookz order by pubdate desc '.
       'limit ?,?');
 
   $start = ($page-1)*EPP;
   $num = EPP;
   $stmt->bind_param('dd', $start, $num);
 
   $stmt->execute();
   $stmt->bind_result($id, $username, $message, $pubdate);
   while ($stmt->fetch()) {
     
       echo '<h2>'.$username.'</h2>';
       echo '<p>'.$message.'</p>';
       echo '<p>'.date('d.m.Y H:i',strtotime($pubdate)).'</p>';
   }
 
   $stmt->close();
   echo $nav;
   
}
 
function show_form() {
   ?>
 
  <form action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post"
       enctype="application/www-form-urlencoded">
 
   <p>input username <input type="text" name="username"></p>
   input message<br/> <textarea name="message"></textarea>
     <br/><input type="submit" name="submit" value="send" />
  </form>
 
<?php
}

Initial URL


Initial Description
Guestbook for interviews

Initial Title
Guestbook for interviews

Initial Tags


Initial Language
PHP