当我使用fetchAll
将整个列放入数组时,我的代码会获取前两列并将这些列放入数组中。但是,当我尝试使用最后的第三列时,它会给我一个空白数组,我的代码如下所示。
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test"; // Table name
// Connect to server and select databse.
$con = new PDO('mysql:host=localhost;dbname=test', $username, $password );
// username and password sent from form
$sth = $con->prepare("SELECT range FROM test");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
现在当我们更换范围而不是nr时,我得到这个输出
Fetch all of the remaining rows in the result set: Array ( [0] => Array ( [nr] => 1 [0] => 1 ) [1] => Array ( [nr] => 2 [0] => 2 ) [2] => Array ( [nr] => 3 [0] => 3 ) [3] => Array ( [nr] => 4 [0] => 4 ) )
然而,当我们离开范围时,我们得到了
Fetch all of the remaining rows in the result set: Array ( )
答案 0 :(得分:1)
SELECT nr FROM test
的工作原因和SELECT range FROM test
之所以不是因为range
是MySQL中的reserved keyword。用反引号(`)围绕它,以便在列名中使用保留关键字:
SELECT `range` FROM test
// ^ ^ Nessesary when using reserved keywords