需要有关OOP PHP MySQL连接的建议

时间:2016-12-01 13:16:56

标签: php mysql oop mysqli

所以我写了一个简单的MySQLi类(从不同的教程中删除+我自己的知识),我希望你指出任何错误和/或我应该添加/更改/删除的内容。十分感谢。这是代码:

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 />";
            }
        }
    } 
?>

1 个答案:

答案 0 :(得分:-1)

Stack Overflow不是代码审查网站,但仍然如此。让代码为你逃避是不是更好?你确定你想要为每一个变量手动编写逃生调用(存在忘记的风险),而不是像这样的简单线

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