Location: PHPKode > scripts > Comments script with pagination > comm/class.BaseCM.php
<?php
// Start BaseCM class
class BaseCM {
  // properties
  static protected $conn = false;            // stores the connection to mysql
  protected $conn_data = array();            // to store data for connecting to database
  public $affected_rows = 0;        // number of affected, or returned rows in SQL query
  public $last_insertid;            // stores the last ID in an AUTO_INCREMENT column, after Insert query
  public $clsite;                    // store the texts for site according to language set
  protected $site;                  // website name
  public $dirbase = '';                 // the directory that contains the classes for this script
  protected $ip;                    // the user IP
  public $eror = false;          // to store and check for errors

  // constructor (receives data for connecting to mysql)
  public function __construct($conn_data) {
    $this->clsite = $GLOBALS['clsite'];     // store in property the text for language
    $this->dirbase = dirname($_SERVER['SCRIPT_NAME']);

    // if the parameter is an array
    if(is_array($conn_data)) {
      $this->conn_data = $conn_data;        // stores data for connection
      $this->ip = isset($_COOKIE['ip']) ? $_COOKIE['ip'] : $_SERVER['REMOTE_ADDR'];
      $this->site = $_SERVER['SERVER_NAME'];
    }
    else $this->setEror($this->clsite['eror_base']['construct']);
  }

  // for connecting to mysql
  protected function setConn($conn_data) {
    try {
      // Connect and create the PDO object
      self::$conn = new PDO("mysql:host=".$conn_data['host']."; dbname=".$conn_data['bdname'], $conn_data['user'], $conn_data['pass']);

      // Sets to handle the errors in the ERRMODE_EXCEPTION mode
      self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      self::$conn->exec('SET CHARACTER SET utf8');      // Sets encoding UTF-8
      
    }
    catch(PDOException $e) {
      $this->setEror($this->clsite['eror_base']['setconn']. $e->getMessage());
    }
  }

  // Performs SQL queries
  public function sqlExecute($sql) {
    if(self::$conn===false OR self::$conn===NULL) $this->setConn($this->conn_data);      // sets the connection to mysql
    $re = true;           // the value to be returned

    // if there is a connection set ($conn property not false)
    if(self::$conn !== false) {
      // gets the first word in $sql, to determine whenb SELECT query
      $ar_mode = explode(' ', trim($sql), 2);
      $mode = strtolower($ar_mode[0]);

      // performs the query and get returned data
      try {
        if($sqlprep = self::$conn->prepare($sql)) {
          // execute query
          if($sqlprep->execute()) {
            // if $mode is 'select', gets the result_set to return
            if($mode == 'select') {
              $re = array();
              // if fetch() returns at least one row (not false), adds the rows in $re for return
              if(($row = $sqlprep->fetch()) !== false){
                do {
                  // check each column if it has numeric value, to cenvert it from "string"
                  foreach($row AS $k=>$v) {
                    if(is_numeric($v)) $row[$k] = $v + 0;
                  }
                  $re[] = $row;
                }
                while($row = $sqlprep->fetch());
              }
              $this->affected_rows = count($re);                   // number of returned rows
            }
            else $this->affected_rows = $sqlprep->rowCount();      // affected rows for Insert, Update, Delete

            // if Insert query, stores the last insert ID
            if($mode == 'insert') $this->last_insertid = self::$conn->lastInsertId();
          }
          else $this->setEror($this->clsite['eror_base']['sqlexecute']);
        }
        else {
          $eror = self::$conn->errorInfo();
          $this->setEror('Error: '. $eror[2]);
        }
      }
      catch(PDOException $e) {
        $this->setEror($e->getMessage());
      }
    }

    // sets to return false in case of error
    if($this->eror !== false) $re = false;
    return $re;
  }

  // this method Upload files, save in database its name and path, and return it
  protected function uploadFile($filedata, $frule, $fileup, $sql=false) {
    $err = '';        // will store the errors
    $reout = '';      // data returned by this method

    // gets file extension
    $splitimg = explode('.', strtolower($filedata['name']));
    $ext = end($splitimg);

    list($width, $height) = getimagesize($filedata['tmp_name']);     // gets image width and height

    // checks the file to match allowed rules
    if(!in_array($ext, $frule['allowext'])) $err .= sprintf($this->clsite['eror_base']['upext'], $filedata['name']);
    if(isset($frule['maxsize']) AND $filedata['size']>=($frule['maxsize']*1000)) $err .= sprintf($this->clsite['eror_base']['upmaxsize'], $filedata['name'], $frule['maxsize']);
    if((isset($frule['width']) AND isset($frule['height'])) AND ($width>=$frule['width'] OR $height>=$frule['height'])) $err .= sprintf($this->clsite['eror_base']['upimgwh'], $frule['width'], $frule['height']);

    // if no error, performs Upload, otherwise sets $eror and returns false
    if($err == '') {
      if(move_uploaded_file($filedata['tmp_name'], $fileup)) {
        $reout .= $fileup;

        // if $sql to add the file name in database, performs the query
        if($sql AND !$this->sqlExecute($sql)) $reout .= $this->clsite['eror_base']['upfiledb']. $this->eror;
      }
      else $reout .= sprintf($this->clsite['eror_base']['upfile'], $filedata['name']);
    }
    else {
      $this->setEror($err);
      $reout = false;
    }

    return $reout;
  }

  // the method  to send e-mail (with html code, and utf-8 encoding)
  protected function sendMail($to, $from, $from_name, $sub, $msgs){
    $eol = "\r\n";             // Used for new line
    $re = true;                // variable to return
    if(!is_array($to)) $to = array($to);     // makes sure $to is array
    if(!is_array($msgs)) $msgs = array($msgs);     // makes sure $msg is array
    $nrto = count($to);

    // Sets headers for email, end subject ($sub) with base for utf-8
    $headers = "From: $from_name <". $from . ">".$eol;
    $headers .= "MIME-Version: 1.0". $eol;
    $headers .= "Content-type: text/html; charset=utf-8". $eol;
    $headers .="Content-Transfer-Encoding: 8bit";
    $sub = "=?utf-8?B?".base64_encode($sub)."?=";

    // traverse $to and send email to each e-mail address in $to
    for($i=0; $i<$nrto; $i++) {
      // pause 1 sec on each 11 e-mail, maximum 50 mails
      if(($i%11) === 0) sleep(1);
      else if($i > 50) break;

      $msg = isset($msgs[$i]) ? $msgs[$i] : $msgs[0];    // gets current mesage in $msgs, or first if no $msg[$i]

      // If the mail cant be sent, sets $re to false, and stop for()
      if (!mail($to[$i], $sub, $msg, $headers)) { $re = false; break; }
    }

    return $re;
  }

  // sets and returns a verification code (captcha)
  public function setCaptcha($ses) {
    $datestr = date("j-F-Y, g:i");              // string with current date-time
    $datestr = md5($datestr);                   // encode the $datestr

    // if seesion exists, delete it and sets session with a code from $datestr
    if(isset($_SESSION[$ses])) { unset($_SESSION[$ses]); }
    $_SESSION[$ses] = substr($datestr, 3, 5);

    return $_SESSION[$ses];        // returns the session with captcha
  }

  // Function to convert BBCODE in HTML tags
  public function formatBbcode($str) {
    // characters that represents bbcode, and smiles
    $bbcode = array(
    '/\[b\](.*?)\[\/b\]/is', '/\[i\](.*?)\[\/i\]/is', '/\[u\](.*?)\[\/u\]/is',      // for format text
    '/\[url\=(.*?)\](.*?)\[\/url\]/is',            // for URL
    '/\[imup=(.*?)\](.*?)\[\/imup\]/is',          // image uploaded in comments
    '/\[br\]/', '/\[brc\]/is',                    // tag <br> with class
    '/:\)/i', '/:\(/i', '/:P/i', '/:D/i', '/:S/i', '/:O/i', '/:=\)/i', '/:\|H/i', '/:X/i', '/:\-\*/i');

    // HTML code that replace bbcode, and smiles characters
    $htmlcode = array(
    '<b>$1</b>', '<i>$1</i>', '<u>$1</u>',             // format text
    '<a target="_blank" href="$1" title="$2">$2</a>',        // URL
    '<div class="upimg"><img width="125" alt="$2" src="$1" /></div>',      // image uploaded in comments
    '<br/>', '<br class="clr"/>',                  // tags <br>
    '<img src="icos/0.gif" alt=":)" border="0" />',
    '<img src="icos/1.gif" alt=":(" border="0" />',
    '<img src="icos/2.gif" alt=":P" border="0" />',
    '<img src="icos/3.gif" alt=":D" border="0" />',
    '<img src="icos/4.gif" alt=":S" border="0" />',
    '<img src="icos/5.gif" alt=":O" border="0" />',
    '<img src="icos/6.gif" alt=":=)" border="0" />',
    '<img src="icos/7.gif" alt=":|H" border="0" />',
    '<img src="icos/8.gif" alt=":X" border="0" />',
    '<img src="icos/9.gif" alt=":-*" border="0" />'
    );

    $str = preg_replace($bbcode, $htmlcode, $str);   // perform replaceament

    return $str;
  }

  // sets the $eror property
  protected function setEror($eror) {
    $this->eror = '<div class="eror">Error: '. $eror. '</div>';
  }
}
Return current item: Comments script with pagination