【问题标题】:Mysqli_query and mysqli_fetch_assoc are nullmysqli_query 和 mysqli_fetch_assoc 为空
【发布时间】:2012-06-26 01:40:51
【问题描述】:

对于一个学校项目,我正在创建一个虚构的网上银行网站,该网站可以访问学校的数据库以获取虚构的帐户信息。每次查看帐户时,我都会收到两个 mysqli 错误。一个在 person.class.php 的第 26 行,另一个在 veiwaccounts.php 的第 52 行 我在我的 person 类中追踪了该错误的主要原因,但似乎无法以任何方式修复它。错误是

警告:mysqli_query() 期望参数 1 为 mysqli,在第 26 行的 .../person.class.php 中给出 null
警告:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result,在第 52 行的 .../viewaccounts.php 中给出 null

以下是 viewaccounts.php 文件中的一些代码示例:

if($currentMember)
{
    $currentMember = new Person($memberid);
    $accounts =  $currentMember->retrieve_all_accounts();

    //HERE IS WHERE THE PROBLEM IS $accounts = $currentMember->retrieve_all_accounts(); 

    //Loop through accounts
    while($account = mysqli_fetch_assoc($accounts)) {
        //Retrieve balance
        $bankaccount = new Bankaccount($account['BankAccountID']);
        $bankaccount->connection = $conn;
        $balance = mysqli_fetch_assoc($bankaccount->retrieve_current_balance());

这是person类文件的代码:

public function retrieve_all_accounts() {
    $accounts_query = "SELECT BankAccountID FROM BankAccount WHERE UserID = " .$this->memberid;
    $result = mysqli_query($this->connection, $accounts_query);
    return $result;
}

【问题讨论】:

  • 我在顶部添加了有关错误的更多信息。
  • 你是如何在这个类中初始化连接的?也许你需要一个全局变量来做到这一点

标签: php mysqli


【解决方案1】:

改变

    //Accounts
    $currentMember->connection = $conn;

    //instantiating class here since suggested code from video fails to do it.


if($currentMember)
{
    $currentMember = new Person($memberid);
    $accounts =  $currentMember->retrieve_all_accounts();

}else
{
    echo "<p>not working</p>";
}

if(!$currentMember) {
  $currentMember = new Person($memberid);
}
$currentMember->connection = $conn;
$accounts =  $currentMember->retrieve_all_accounts();

为了便于阅读,我还将它转移到第一个 PHP 代码块中。

只有当$currentMember 的计算结果为TRUE 时,您才实例化一个新的Person - 如果unserialize() 调用失败,$currentMember 的计算结果为FALSE,此时您应该创建一个新对象。

您还首先分配了connection 属性,当您创建新的Person 时,该属性将被销毁,您可能每次都这样做,否则您会看到更多警告。

您还应该重构测试Person 是否保存在$_SESSION 中的整个逻辑 - 首先,会话将序列化对象本身,因此您不需要调用serialize()/unserialize()。您应该做的是定义一个__autoload() 函数并将对象实例存储在$_SESSION 中。

我还注意到,您的开发服务器似乎开启了short_open_tag - 将其关闭,使用它是不好的做法,因为它在现实世界中几乎无处不在。

【讨论】:

    【解决方案2】:

    您的Database 对象在初始化连接时似乎有问题。它可能没有连接,因为错误表明您没有向mysli_query() 提供mysqli 对象。

    尝试查看Database 类中的mysqli_connect_error()mysqli_connect_errno(),以确定在连接和从那里工作时是否出现错误。

    【讨论】:

      【解决方案3】:

      您正在使用来自 $memberid 变量的成员 ID 实例化您的 person 类。尝试在此处传递$memberid 的值[在此处传递值以实例化person 类的对象] 并使用var_dump 来调试它是否真的返回任何值。 并在实例化对象后放置$currentMember-&gt;connection = $conn;。很可能您的问题是在这里引起的。您试图在实例化之前访问类 person 的公共变量连接。

      【讨论】:

        猜你喜欢
        • 2016-02-21
        • 2014-03-09
        • 1970-01-01
        • 2015-12-08
        • 2012-08-25
        • 2015-04-14
        • 1970-01-01
        • 2016-09-07
        • 1970-01-01
        相关资源
        最近更新 更多