0

So I wrote a simple MySQLi class (scratched from different tutorials + my own knowledge) and I'd like you to point out any errors and/or what should I add/change/remove. Big thanks. Here's the code:

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)."'";
        }
    };
?>

Example usage

<?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 Answers1

-1

Stack Overflow is not a code review site but still. Isn't it better to make your code to do escaping for you? Are you sure you want write that escape call by hand for every single variable (with a risk of forgetting that), instead of just a simple line like this

    $conn = new Database;
    $rows = $conn->select("SELECT * FROM users WHERE email = ?", [$_POST["email"]]);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345