2012-02-15 61 views
6

我試圖創建在PHP中使用的mysqli MySQL數據庫的連接。當我一個獨立的頁面上執行以下代碼:新的mysqli對象爲空

<?php 
ini_set('display_errors', 'On'); 
error_reporting(E_ALL); 

$link = new mysqli('localhost', 'myuser', 'mypass', 'dbname'); 
var_dump($link); 

我得到的輸出是一個空的mysqli對象,其中的所有屬性都爲空。沒有錯誤或任何顯示。

我還沒有看到在Apache或MySQL日誌的所有條目。我對這個人很迷茫。

+0

試'$鏈接=新的mysqli( '本地主機', '爲myuser', '爲mypass', 'DBNAME')或死亡(mysqli_error());' – crush 2012-02-15 22:18:13

+1

@crush :我想你的意思是'$ link = new mysqli('localhost','myuser','mypass','dbname')或die(mysqli_connect_error());'。 'mysqli_error()'函數需要一個鏈接標識符作爲其參數。 – 2012-02-15 22:24:37

+0

@Justin,我改變了你的建議,它根本沒有改變。在實例化mysqli對象之後,假設沒有錯誤,mysql_connect_error函數返回null。儘管mysqli對象的屬性都是null。當我轉儲$ link時,得到: – 2012-02-15 22:37:45

回答

8

我也有這個問題,快要瘋了試圖調試。事實證明,有時出於任何原因,mysqli對象沒有被填充,但直接訪問它的屬性仍然執行它後面的本地代碼。因此,即使整個mysqli對象的var_dump顯示爲空屬性,如果您單獨訪問它們,它們仍然存在。如果errorno原來是錯誤的,那麼您可能已經執行了一個有效的查詢,其中包含一個空的結果集,而您並不期待。希望這可以幫助。

$mysqli = mysqli_connect('localhost', 'root', '', 'test', 3306); 

var_dump($mysqli); 

var_dump($mysqli->client_info); 
var_dump($mysqli->client_version); 
var_dump($mysqli->info); 

和輸出:

object(mysqli)[1] 
    public 'affected_rows' => null 
    public 'client_info' => null 
    public 'client_version' => null 
    public 'connect_errno' => null 
    public 'connect_error' => null 
    public 'errno' => null 
    public 'error' => null 
    public 'field_count' => null 
    public 'host_info' => null 
    public 'info' => null 


public 'insert_id' => null 
    public 'server_info' => null 
    public 'server_version' => null 
    public 'stat' => null 
    public 'sqlstate' => null 
    public 'protocol_version' => null 
    public 'thread_id' => null 
    public 'warning_count' => null 

string 'mysqlnd 5.0.8-dev - 20102224 - $Revision: 321634 $' (length=50) 
int 50008 
null 
int 0 
string 'localhost via TCP/IP' (length=20) 
string '5.5.20-log' (length=10) 
int 50520 
+0

剛剛遇到了這個問題,並且你的解決方案工作,但我確實發現'print_r'也會適當地打印出這個對象。 – user3158900 2014-06-06 13:52:56

1

我知道這是一個有點老,但任何人誰還有這是一個反覆出現的問題,從user3158900到danperron的職位評論有解決方案。我在這裏重新張貼,使其更加明顯。此外,一些示例代碼包括:

global $mysqli; //assuming you've already created your $mysqli object 
$mysqli->query("INSERT INTO users SET username='jim' and password='somehash'"); 
var_dump($mysqli); //prints the full object but all the values are null 

//the following code prints the full object with appropriate values such as 
//insert_id, affected_rows, etc 
//view http://pastebin.com/Mgd2CZsM for an example of this output 
echo "<pre>" . print_r($mysqli, true). "</pre>";