php pdo database写法

Published
September 19, 2022
浏览次数 :  12

<?php 
class Database {

  private $db_host = 'localhost';
  private $db_name = 'db_user_system';
  private $db_username = 'root';
  private $db_password = '*******';

  public $conn;

  public function __construct() {

    try {
      $this->conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name",$this->db_username,$this->db_password);
      $this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e ) {
      echo 'Error : ' . $e->getMessage();
    }
    return $this->conn;
  }

  public function testInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }

  #error success message alert 
  public function showMessage($type,$message) {
    return '<div class="alert alert-'.$type.' alert-dismissible fade show" role="alert">
    <strong class="text-center">'.$message.'</strong>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>';

  }

  public function timeInAgo($timestamp)
  {
    // code...
    date_default_timezone_set('Asia/Shanghai');

    //convert timestamp into seconds this is seconeds!! 
    $timestamp = strtotime($timestamp);
    $time = time() - $timestamp;

    //switch times
    switch($time) {
      //seconds
      case $time < 60 : 
      return "Just Now";
      break;

      //minutes
      case $time >= 60 && $time < 3600 : 
      return (round($time / 60) == 1) ? 'a Minitue ago' : round($time / 60) . ' Minitues Ago';
      break;

      //hours 86400 === 24 hours while 3600 === 1 hour 
      case $time >=3600 && $time < 86400 : 
      return (round($time / 3600) == 1) ? 'an hour ago' : round($time / 3600) . ' hours Ago';
      break;

      //days
      case $time >= 86400 && $time < 604800 : 
      return (round($time / 86400) == 1) ? 'one day ago' : round($time / 86400) . ' days Ago';
      break;

      //weeks
      case $time >= 604800 && $time < 2600640 : 
      return (round($time / 604800) == 1) ? 'one week ago' : round($time / 604800) . ' weeks Ago';
      break;

      //month 
      case $time >= 2600640 && $time < 31207680 : 
      return (round($time / 2600640) == 1) ? 'one month ago' : round($time / 2600640) . ' months Ago';
      break;

      //years 
      case $time >= 31207680 : 
      return (round($time / 31207680) == 1) ? 'one year ago' : round($time / 31207680) . ' years Ago';
      break;
    }
  }
}

Top