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 />";
}
}
}
?>
什麼問題只是一個簡單的線? –
第一個建議 - 瞭解__準備報表__ –
您是否試圖讓您的dbclass成爲單例類? –