2016-12-01 68 views
0

因此,我編寫了一個簡單的MySQLi類(從不同的教程+我自己的知識中抓取),並且希望您指出所有錯誤和/或添加/更改/刪除的內容。十分感謝。下面的代碼:需要關於OOP的建議PHP MySQL連接

dbclass.php

<?php 
    class Database 
    { 
     protected static $connection; 

     public function __construct() 
     { 
      self::$connection = $this->connect(); 
     } 

     public function __destruct() 
     { 
      self::$connection->close(); 
     } 

     private function connect() 
     { 
      if (!isset(self::$connection)) 
      { 
       $config = parse_ini_file("dbsettings.ini"); 
       self::$connection = new mysqli($config["host"], $config["username"], $config["password"], $config["database"]); 
      } 

      if (!self::$connection) 
       return false; 

      return self::$connection; 
     } 

     public function query($query) 
     { 
      $result = self::$connection->query($query); 
      return $result; 
     } 

     public function select($query) 
     { 
      $rows = array(); 
      $result = $this->query($query); 

      if (!$result) 
       return false; 

      while ($row = $result->fetch_assoc()) 
      { 
       $rows[] = $row; 
      } 

      return $rows; 
     } 

     public function escape($value) 
     { 
      $value = htmlspecialchars($value, ENT_QUOTES, "UTF-8"); 
      return "'".self::$connection->real_escape_string($value)."'"; 
     } 
    }; 
?> 

用法示例

<?php 
    require("php/require/dbclass.php"); 

    if (isset($_POST["login"])) 
    { 
     $conn = new Database; 

     $email = $conn->escape($_POST["email"]); 
     $password = $conn->escape($_POST["password"]); 

     $rows = $conn->select("SELECT * FROM users WHERE email = $email"); 

     if ($rows) 
     { 
      foreach ($rows as $row) 
      { 
       echo $row["username"]."<br />"; 
      } 
     } 
    } 
?> 
+0

什麼問題只是一個簡單的線? –

+3

第一個建議 - 瞭解__準備報表__ –

+0

您是否試圖讓您的dbclass成爲單例類? –

回答

-1

堆棧溢出不是一個代碼審查的網站,但仍。讓你的代碼爲你逃避是不是更好?你確定你想手工編寫的每一個變量逃生通話(與風險忘記是),而不是像這樣

$conn = new Database; 
    $rows = $conn->select("SELECT * FROM users WHERE email = ?", [$_POST["email"]]); 
+0

不知道,感謝: ) – daavid245