首页 > 解决方案 > 如何修改我的 PHP 数据库提取类以使用 MySQLi

问题描述

我收到一条警告,说明:

mysqli_num_rows() 期望参数 1 为 mysqli_result

自从我使用 PHP 以来已经有一段时间了,这让我很难弄清楚为什么 MySQLReturn 类中的 size 函数让我感到悲伤。这是我多年前使用的一个旧类,并尽我所能对其进行了修改,以使用php7and MySQLi

    <?php

class MySQL {

private $host;
private $dbUser;
private $dbPass;
private $dbName;
private $dbConn;
private $connectError;

public function __construct($host,$dbUser,$dbPass,$dbName) {
    $this->host=$host;
    $this->dbUser=$dbUser;
    $this->dbPass=$dbPass;
    $this->dbName=$dbName;
    $this->connectToDb();
}

public function __destruct() {
}

public function connectToDb () {
    // Make connection to MySQL server
    if (!$this->dbConn = mysqli_connect($this->host,$this->dbUser,$this->dbPass)) {
        trigger_error('Could not connect to server');
        $this->connectError=true;
    // Select database
    } else if (!mysqli_select_db($this->dbConn,$this->dbName)) {
        trigger_error('Could not select database');
        $this->connectError=true;
    }
}

public function isError () {
    if ($this->connectError)
        return true;
    $error=mysqli_error($this->dbConn);
    if (empty($error))
        return false;
    else
        return true;
}


public function query($sql) {
 if (!$queryResource=mysqli_query($this->dbConn,$sql)) trigger_error ('Query failed: '.mysqli_error($this->dbConn).' SQL: '.$sql);
        $result = new MySQLReturn($this,$queryResource);
        return $result;
}
}

class MySQLReturn {

private $mysql;

private $query;

public function MySQLResult($mysql,$query) {
    $this->mysql=$mysql;
    $this->query=$query;
}

public function fetch() {
    if ($row=mysqli_fetch_array($this->query,MYSQL_ASSOC) ) {
        return $row;
    } else if ( $this->size() > 0 ) {
        mysqli_data_seek($this->query,0);
        return false;
    } else {
        return false;
    }
}

public function size() {
    return mysqli_num_rows($this->query);
}

public function insertID() {
    return mysqli_insert_id($this->mysql->dbConn);
}

public function isError() {
    return $this->mysql->isError();
}
}
?>

这就是我访问类函数的方式;

    <?php
$db = new MySQL($dbhost,$dbuser,$dbpass,$dbmain);
$authsql = $db->query("SELECT * FROM users WHERE email='".$uid."' AND password=MD5('".$pwd."')");

if ($authsql->size() >= '1') {
$logindtsql = $db->query("UPDATE users SET last_login=CURRENT_TIMESTAMP WHERE email='".$uid."' AND password=MD5('".$pwd."')");
$authsqlrow = $authsql->fetch();
extract($authsqlrow);
}

if ($authsql->size() == 0) {
   unset($_SESSION['uid']);
   unset($_SESSION['pwd']);
   session_destroy();
}
?>

我没有得到查询的大小

标签: phpoopmysqli

解决方案


改变了

public function MySQLResult($mysql,$query) {
    $this->mysql=$mysql;
    $this->query=$query;
}

public function __construct($mysql,$query) {
    $this->mysql=$mysql;
    $this->query=$query;
}

奇迹般有效


推荐阅读