mysqli :: query():无法获取mysqli

cod*_*iac 26 php mysql mysqli

警告:mysqli :: query():无法在第43行的C:\ Program Files(x86)\ EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php中获取mysqli

以下是我的连接文件:

<?php
if(!isset($_SESSION)) 
{ 
    session_start(); 
}  

// Create array to hold error messages (if any)
$ErrorMsgs = array();

// Create new mysql connection object
$DBConnect = @new mysqli("localhost","root@localhost", 
            NULL,"Ladle");

// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {

    // Add error to errors array
    $ErrorMsgs[]="The database server is not available.".
               " Connect Error is ".$DBConnect->connect_errno." ".
               $DBConnect->connect_error.".";
}
?>
Run Code Online (Sandbox Code Playgroud)

这是我的班级:

 <?php 
    class EventCalendar {
        private $DBConnect = NULL;

        function __construct() {
            // Include the database connection data
            include("inc_LadleDB.php");
            $this->DBConnect = $DBConnect;  
        }

        function __destruct() {
            if (!$this->DBConnect->connect_error) {
                $this->DBConnect->close();
            }
        }

        function __wakeup() {
            // Include the database connection data
            include("inc_LadleDB.php");     
            $this->DBConnect = $DBConnect;
        }


        // Function to add events to Zodiac calendar
        public function addEvent($Date, $Title, $Description) {
            // Check to see if the required fields of Date and Title have been entered
            if ((!empty($Date)) && (!empty($Title))) {
                /* if all fields are complete then they are 
                   inserted into the Zodiac event_calendar table */
                $SQLString = "INSERT INTO tblSignUps".
                           " (EventDate, Title, Description) ".
                           " VALUES('$Date', '$Title', '".
                            $Description."')";

                // Store query results in a variable
                $QueryResult = $this->DBConnect->query($SQLString);
Run Code Online (Sandbox Code Playgroud)

我对OOP PHP不太满意,我不确定为什么会出现这个错误.我从其他地方提取了这个代码,我唯一改变的是@new mysqli参数.任何人都可以帮我理解出了什么问题吗?

T.T*_*dua 74

你太早关闭连接了DBconnection->close();!在你的询问后做它!


说明:请勿将...->close();__destruct(),因为连接变得立即关闭每当加载完毕.


Ayc*_*şıt 8

错误的原因是mysqli对象的初始化错误.真正的结构将是这样的:

$DBConnect = new mysqli("localhost","root","","Ladle");
Run Code Online (Sandbox Code Playgroud)

  • 我想知道社区是否可以删除这个"答案". (10认同)
  • 你能解释一下为什么原始代码是“错误的”?如果凭据错误(这是我看到的唯一更改),则应该有一个明确的错误消息 (2认同)
  • @AycanYaşıt,但在这种情况下,当提供错误的凭据时,您会收到错误消息“无法获取 mysqli”吗?此外,文档指出,当不使用参数时,将选择没有密码的用户 (2认同)

Rat*_*rty 5

我有同样的问题。我将 mysqli 对象中的 localhost 参数更改为“127.0.0.1”,而不是写入“localhost”。有效; 我不确定如何或为什么。

$db_connection = new mysqli("127.0.0.1","root","","db_name");
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。