2014-07-22 53 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

相关问题