2014-07-22 54 views
0

我正在構建一個用於將數據插入到MySQL數據庫的Web應用程序。我使用PHP的PDO API來查詢數據庫以獲取自動遞增主鍵。當我在MySQL控制檯中運行查詢時,它會生成正確的輸出。但是當我嘗試在PHP中運行查詢時,它將返回null。SQL查詢在PHP中返回空值,但在MySQL中的結果爲正確

查詢:

mysql> SELECT Auto_Increment FROM information_schema.tables WHERE table_name='charlist'; 

結果在MySQL控制檯:

+----------------+ 
| Auto_Increment | 
+----------------+ 
|    7 | 
+----------------+ 

相關PHP代碼:

// Configuration. 
    $username = "root"; 
    $password = "root"; 
    $hostname = "localhost"; 
    $dbname = "asoiaf"; 
    $tablename = "charlist"; 

    // Opens a connection to the database. 
    try { 
     $conn = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    } catch(PDOException $e) { 
     echo $e->getmessage(); 
    } 

    // Gets all the information from POST. 
    $autoidquery = "SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'"; 
    $id = $conn->query("SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'"); 
    // This should output the auto-incremented primary key, but nothing is output. 
    echo $id."<br>Hello world"; 

沒有在頁面上輸出,但它應該輸出自動遞增的id,然後是「Hello world」。我看不到任何我輸入的拼寫錯誤。爲什麼查詢可以在控制檯中工作,但不在PHP中?

+1

我相信在這種情況下'$ id'會是一個結果集,所以試着使用'$ id [0] ['Auto_Increment']來訪問它。或者,嘗試執行'var_dump($ id)'來查看變量包含的內容。 – Supericy

+0

像這樣? 'echo $ id [0] ['Auto_Increment'];'也沒有輸出任何內容:/。 – Lou

+0

有趣。當我做了var_dump,它輸出以下內容,我不知道它是什麼意思:'object(PDOStatement)#2(1){[「queryString」] => string(80)「SELECT Auto_Increment FROM information_schema.tables WHERE table_name ='charlist'「}'。 – Lou

回答

1

你需要獲取結果

$qry = $conn->query("SELECT Auto_Increment FROM information_schema.tables WHERE table_name='$tablename'"); 
$result = $qry->fetch(); 
$id = $result['Auto_Increment']; 
echo $id."<br>Hello world"; 
+0

完美地工作。大! – Lou

1

使用: 的print_r($ ID);

查看查詢結果的內容。查詢結果的輸出是一個數組。你sh

相關問題