不知道如何为我的两个类创建全局mysql连接


Not sure how to create global Mysqli connection for my two classes

我以前问过这个问题,我被重复的问题打了耳光…但有趣的是,重复问题的答案是我不理解的,也不知道如何在我的代码中实现它。

"重复"问题的答案提到PDO连接,目前我没有线索或理解的东西。

我已经想出了,在帮助下,写两个类,一个提交数据到MySql数据库,另一个搜索MySql数据库的列。

我的问题是实际上把两个类放在一个php文件中,并允许它们都只使用一个连接类。

这两个类都以不同的格式编写,我试图理解如何将它们组合成一个,或者至少使用一个连接类而不是每个使用自己的连接函数,我知道,这是糟糕的php标准…

答案我被指出要提到this的使用:

  $pdo = new PDO('something');
  function foo() {
     global $pdo;
     $pdo->prepare('...');
  }

我的问题是……我没有使用PDO…请协助和解释我需要改变什么,使这两个类使用一个Db连接…

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

function db_connect() {
    // Define connection as a static variable, to avoid connecting more than once 
    static $connection;
    // Try and connect to the database, if a connection has not been established yet
    if(!isset($connection)) {
        $connection = mysqli_connect('localhost','user','pass','resrequest_db1');
    }
    // If connection was not successful, handle the error
    if($connection === false) {
        // Handle error - notify administrator, log to a file, show an error screen, etc.
        return mysqli_connect_error(); 
    }
    return $connection;
}
function db_query($query) {
    // Connect to the database
    $connection = db_connect();
    // Query the database
    $result = mysqli_query($connection,$query);
    return $result;
}    

class booking
{
  private $error;
  private $success;
  private $form_data = array();
  function __construct()
  {
      //check if the booking form has been submitted
      if (isset($_POST['submit_form'])) {
          foreach ($_POST as $field => $value)
              $this->form_data[$field] = $value;
          //start perform the validation once the form has been submitted
          $this->validateInformation();
      }
      //check to see if the mail has been sent, and then display a success message
      if (isset($_GET['m']) && $_GET['m'] == "s") {
          $this->error = "<div class='alert alert-success'>Thank You! We received your booking</div>";
      }
      //display error if any
      if (!empty ($this->error) || !empty ($this->success))
          $this->displayMessage(!empty($this->error) ? $this->error : (!empty($this->success) ? $this->success : ''), false);
  }
  /********************************************************
   * This function retrieves data for booking form
   * and performs validation
   *******************************************************/
  private function validateInformation()
  {
      // check if person provided his name
      if (empty($this->form_data['b_name'])) {
          $this->error .= '<li>You must enter your name.</li>';
      }
      // check if person provided his email
      if (empty($this->form_data['email'])) {
          $this->error .= '<li>You must enter your email.</li>';
      }
      // check if the email address provided by user is in correct format
      if (!empty($this->form_data['email'])) {
          if (!preg_match("/(['w'-]+'@['w'-]+'.['w'-]+)/", $this->form_data['email'])) {
              $this->error .= '<li>Email format your entered is not valid.</li>';
          }
      }
      // check if contact_number is empty
      if (empty($this->form_data['contact_number'])) {
          $this->error .= '<li>Please enter a contact number.</li>';
      }
      //Check for a valid phone number  (Only numbers between 7 & 20 caracters)
      if (!empty($this->form_data['phone'])) {
          $phone = $this->form_data['phone'];
          $pattern = "/^[0-9'_]{10,20}/";
          if (preg_match($pattern,$phone)){ 
            $phone = $this->form_data['phone'];}
            else{ $errors[] = 'Your Phone number can only be numbers.';}
          } else {$errors[] = 'You forgot to enter your Phone number.';}
      // check if person provided total rooms
      if (empty($this->form_data['nr_rooms'])) {
          $this->error .= '<li>Indicate total rooms.</li>';
      }
      // check if person provided arrival date
      if (empty($this->form_data['arrival'])) {
          $this->error .= '<li>Please select arrival date.</li>';
      }
      // check if person provided departure date
      if (empty($this->form_data['departure'])) {
          $this->error .= '<li>Please select departure date.</li>';
      }
      $this->error = (isset($this->error)) ? "<div class='alert alert-danger'><h4 class='alert-heading'>Attention!</h4>$this->error</div>" : '';
      // if no errors are found, get ready to send the mail
      if (empty($this->error)) {
          $this->dbInsert();
      }
  }
  /********************************************************
   * This function inserts data into Db
   *******************************************************/
  private function dbInsert()
  {
    $b_name=$this->form_data['b_name'];
    $email=$this->form_data['email'];
    $contact_number=$this->form_data['contact_number'];
    $nr_rooms=$this->form_data['nr_rooms'];
    $arrival=$this->form_data['arrival'];
    $departure=$this->form_data['departure'];
    // An insertion query.
    $result = db_query("INSERT INTO bookings (b_name,email,contact_number,nr_rooms,arrival,departure)
            VALUES ('$b_name','$email','$contact_number','$nr_rooms','$arrival','$departure')");
    if($result === false) {
      // Handle failure - log the error, notify administrator, etc.
      $error ="<div class='alert alert-danger'><h4 class='alert-heading'>Attention!</h4>
              Databse error!!!</div>";
    } else {
          $redirect_page = "index.php?m=s";
          header('Location: ' . $redirect_page);
          exit();
    }
  }
  /********************************************************
   * This function displays error if any
   *******************************************************/
  private function displayMessage($error, $exit = true)
  {
      if (!empty($error)) :
          include_once(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . 'header.php');
          echo $error;
          if ($exit) {
              include_once(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . 'footer.php');
              exit();
          }
      endif;
  }
  /********************************************************
   * This function will store the submitted data in case
   * of any error so user does not have to re enter the
   * information which he/she already provided
   *******************************************************/
  public function fetchPost($var)
  {
      return empty($this->form_data[$var]) ? '' : $this->form_data[$var];
  }
}
$booking = new booking();
class search {
  /**
   * MySQLi connection
   * @access private
   * @var object
   */
  private $mysqli;
  /**
   * Constructor
   *
   * This sets up the class
   */
  public function __construct() {
    // Connect to our database and store in $mysqli property
    $this->connect();
  }
  /**
   * Database connection
   * 
   * This connects to our database
   */
  private function connect() {
    $config = parse_ini_file('config.ini');   //<--------------------------- Not to be placed in root directory, done for Resrequest demo
    $this->mysqli = new mysqli( 'localhost', $config['username'],$config['password'],$config['dbname'] );
  }
  /**
   * Search routine
   * 
   * Performs a search
   * 
   * @param string $search_term The search term
   * 
   * @return array/boolen $search_results Array of search results or false
   */
  public function search($search_term) {
    // Sanitize the search term to prevent injection attacks
    $sanitized = $this->mysqli->real_escape_string($search_term);
    // Run the query
    $query = $this->mysqli->query("
      SELECT b_name, email, contact_number, arrival, departure
      FROM bookings
      WHERE b_name LIKE '%{$sanitized}%'
      OR email LIKE '%{$sanitized}%' OR contact_number LIKE '%{$sanitized}%' 
      OR arrival LIKE '%{$sanitized}%' OR departure LIKE '%{$sanitized}%'
    ");
    // Check results
    if ( ! $query->num_rows ) {
      return false;
    }
    // Loop and fetch objects
    while( $row = $query->fetch_object() ) {
      $rows[] = $row;
    }
    // Build our return result
    $search_results = array(
      'count' => $query->num_rows,
      'results' => $rows,
    );
    return $search_results;
  }
}
?>

这是处理此类内容的常用方法。请尝试:

class Database {
    private static $instance;
    private $db;
    private function __construct() {
        $this->db = mysqli_connect('localhost','user','pass','resrequest_db1');
    }
    public static function getInstance() {
        if(self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance->db;
    }
}
class MyClass {
private $db = null;
public function __construct($db){
    $this->db = $db
}
.... your code here 
}
// you create the unique connection here. 
 $db = Database::getInstance();
// call of the class
 $myClass = new MyClass($db);