【问题标题】:I having a problem with the mysqli free() member function我的 mysqli free() 成员函数有问题
【发布时间】:2010-05-09 11:26:11
【问题描述】:

我有这样的代码连接到数据库:

$db = new mysqli("localhost", "user", "pass", "company");

现在当我像这样查询数据库时:

//query calls to a stored procedure 'user_info' 
$result = $db->query("CALL user_info('$instruc', 'c_register', '$eml', '$pass', '')");
if($result->fetch_array())
{
   //use the results
}
$result->close();

$result = $db->query("CALL user_info('$instruc', 's_login', '$eml', '$pass', '')");
if($result->fetch_array())
{
   //use the results
}
$result->close();

我在第一个 $result->close(); 之后收到此错误

致命错误:在...中的非对象上调用成员函数 fetch_array()

为了让我运行这个其他查询,我必须关闭数据库连接并再次连接,然后它才能工作。我想知道是否有一种方法可以运行其他查询,而无需断开连接并重新连接到数据库。

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    free() 会删除所有存储在与结果集相关的数据,但它不会取消设置$result 对象本身,所以$result 仍然设置是完全可以的。

    不过,您应该仍然可以使用 $db 对象启动新查询。释放结果集不应影响数据库对象本身。

    您能否显示在结果对象上运行free() 后失败的查询的完整代码以及它返回的错误?

    【讨论】:

    • @neo close() 关闭数据库连接。使用 free() 代替,它应该可以工作。
    【解决方案2】:

    下面给出一个简单的例子:

    $query='select ml_id, list_name from ml_lists order by list_name asc';
    $squery=$db->query($query);
    
        while($rows=$squery->fetch_assoc()){
            echo $rows['list_name'];
        }
    }
    $squery->close();
    

    【讨论】:

      【解决方案3】:

      添加一些错误处理。如果 mysqli->query 失败,则返回 false,因此 $result 不是对象,因此 Fatal error: Call to a member function xyz() on a non-object.
      在这种情况下,mysqli->error 应该包含错误消息。

      //query calls to a stored procedure 'user_info'
      $result = $db->query("CALL user_info('$instruc', 'c_register', '$eml', '$pass', '')");
      if ( !$result ) {
        die('an error occured: '.$db->error);
      }
      if($result->fetch_array())
      {
        //use the results
      }
      $result->close();
      
      $result = $db->query("CALL user_info('$instruc', 's_login', '$eml', '$pass', '')");
      if ( !$result ) {
        die('an error occured: '.$db->error);
      }
      if($result->fetch_array())
      {
        //use the results
      }
      $result->close();
      

      【讨论】:

      • 我尝试了该代码,现在我得到:“发生错误:命令不同步;您现在无法运行此命令”。
      • 每个$result->close(); 之前的while( $db->next_result() ); 是否可以解决问题?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 2011-09-09
      • 2013-09-25
      相关资源
      最近更新 更多