SQL查询在PHP中返回null,但在MySQL中返回正确的结果
我正在构建一个web应用程序,用于将数据插入MySQL数据库。我正在使用PHP的PDOAPI查询数据库以获得一个自动递增的主键。当我在MySQL控制台中运行查询时,它会生成正确的输出。但是当我尝试用PHP运行查询时,它返回null 查询:SQL查询在PHP中返回null,但在MySQL中返回正确的结果,php,mysql,sql,pdo,auto-increment,Php,Mysql,Sql,Pdo,Auto Increment,我正在构建一个web应用程序,用于将数据插入MySQL数据库。我正在使用PHP的PDOAPI查询数据库以获得一个自动递增的主键。当我在MySQL控制台中运行查询时,它会生成正确的输出。但是当我尝试用PHP运行查询时,它返回null 查询: mysql> SELECT Auto_Increment FROM information_schema.tables WHERE table_name='charlist'; MySQL控制台中的结果: +----------------+ | Au
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中工作?您需要获取结果
$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";
您需要获取结果
$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";
,要访问所需结果,您需要以数组的形式访问结果
echo $id['Auto_Increment'];
或者您可以从语句中获取结果
echo $id->fetchColumn();
或用于以整数形式检索结果
通往罗马的道路很多 ,要访问所需结果,需要以数组形式访问结果
echo $id['Auto_Increment'];
或者您可以从语句中获取结果
echo $id->fetchColumn();
或用于以整数形式检索结果
通往罗马的道路很多 使用:
打印r$id
查看查询结果的内容。查询结果的输出是一个数组。你应该使用:
打印r$id
查看查询结果的内容。查询结果的输出是一个数组。您应该我相信在这种情况下,$id将是一个结果集,所以请尝试使用$id[0]['Auto_Increment']访问它。或者,尝试执行var_dump$id,以查看变量到底包含哪些内容?echo$id[0]['Auto_Increment'];这也没有输出任何内容:/。有趣。当我执行var_dump时,它输出了以下内容,我不知道它的意思:objectPDOStatement2 1{[queryString]=>string80从信息_schema.tables WHERE table_name='charlist'}中选择自动增量。@Sean,为什么要删除答案?我尝试了你的代码,它工作了,解决了我的问题。“我正要接受它。”“对不起。本打算点击编辑,但点击删除,然后我的wifi下降。我已经恢复了我的答案。我相信在这种情况下,$id将是一个结果集,所以请尝试使用$id[0]['Auto_Increment']访问它。或者,尝试执行var_dump$id,以查看变量到底包含哪些内容?echo$id[0]['Auto_Increment'];这也没有输出任何内容:/。有趣。当我执行var_dump时,它输出了以下内容,我不知道它的意思:objectPDOStatement2 1{[queryString]=>string80从信息_schema.tables WHERE table_name='charlist'}中选择自动增量。@Sean,为什么要删除答案?我尝试了你的代码,它工作了,解决了我的问题。“我正要接受它。”“对不起。本打算点击编辑,但点击删除,然后我的wifi下降。我已经恢复了我的答案。效果很好。伟大的工作完美。伟大的