PHP MySQLI OOP不起作用



我想为我的MySQLI OOP寻求帮助。我的MySQLI类如下所示:

Class DB {
    Private $connection;
    Public Function __construct($host = "localhost", $user = "root", $password = "", $db = "social_network") {
        $this->host = $host;
        $this->db = $db;
        $this->user = $user;
        $this->password = $password;
        $this->connection = @new mysqli($this->host, $this->user, $this->password);
        $this->connection->set_charset("UTF-8");
        if($this->connection->connect_errno > 0){
            die('Tietokantapalvelimeen ei saada yhteyttä [' . $this->connection->connect_error . ']');
        } else {
            if(!$this->connection->select_db($db)) {
                die('Tietokantaan ei saada yhteyttä: ' . $this->connection->error);
            }
            return $this->connection;
        } 
    }
    Public Function connect() {
        if(!$this->connection){
            return $this->connection;
        }
        return true;
    }
    Public Function disconnect() {
        if($this->connection){
            $this->connection->kill($this->connection->thread_id);
            $this->connection->close();
        }
        return true;
    }
    Public Function query($sql) {
        return $this->connection->query($sql);
    }
    Public Function result($sql) {
        $query = $this->connection->query($sql);
        if($query){
            $result = array();
            $i = 0;
            while($row = $query->fetch_object()){
                $result[$i] = $row;
                $i++;
            }
            return $result;
        } else {
            return print $this->connection->error;
        }
    }
    Public Function escape_string($sql) {
        return $this->connection->real_escape_string($sql);
    }
    Public Function __destruct() {
        $this->disconnect();
    }
}

示例结果:

$DB = new DB($_CONFIG['host'], $_CONFIG['user'], $_CONFIG['password'], $_CONFIG['db']);
$row = $DB->result("SELECT username, password FROM users WHERE username = T0niiiiii LIMIT 1");

print $row['username'];

我得到错误"'where clause'中的未知列'T0niiiiii'"

那么怎么了?我该怎么解决?或者有人知道现成的MySQLI OOP吗?

如果不使用撇号包装值,MYSQL将"认为"您在引用列。

这应该是你的代码:

$DB->result("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");

你甚至不需要在这里询问,错误信息说明了一切。

关于检索行,您可以这样做:

$query = $DB->query("SELECT username, password FROM users WHERE username = 'T0niiiiii' LIMIT 1");
foreach ($query->result() as $row)
{
   echo $row->username;
   echo $row->password; //Never echo the password, this is just for testing :P
}

最新更新