0

我在 PHP 中的 SQL 查询出现错误。我尝试了多个查询,并且也厌倦了使用 phpMyAdmin 生成的 PHP 代码。谁能帮我这个?

无效查询:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ''sample_table' LIMIT 0, 30' 附近使用正确的语法

这是PHP代码:

//Connect to server
 $connect = mysql_connect("localhost", "root", "");
if (!$connect) {
    die('Not connected : ' . mysql_error());
}

//Connect to DB
$db_selected = mysql_select_db("testing", $connect);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$sql = "SELECT `Name` FROM `sample_table` LIMIT 0, 30 ";

//Query DB table
$sqlQuery = mysql_query($sql, $connect);
if (!$sqlQuery) {
    die('Invalid query: ' . mysql_error());
}

//fetch the results / convert the results into an array
while($rows = mysql_fetch_array($sqlQuery, MYSQL_NUM)) //this is happening
{   
    $name = $rows['name'];
    $age = $rows['age'];
    $ID = $rows['ID'];

    echo "$name<br/>$age<br/>$ID<br/>";
}

mysql_close($connect);

这是我创建的 phpMyAdmin 表的屏幕截图。此表中有许多记录。

phpMyAdmin 截图

4

5 回答 5

1

试试这个

SELECT Name FROM sample_table LIMIT 0, 30 

代替

SELECT Name FROM 'sample_table' LIMIT 0, 30
于 2012-06-25T17:40:47.777 回答
1

改变这个:

$sql = "SELECT Name FROM 'sample_table' LIMIT 0, 30 ";

进入这个:

$sql = "SELECT `Name` FROM `sample_table` LIMIT 0, 30 ";

请注意,我已将 into 更改'`.

顺便说一句,echo语法应该是这样的:

 echo $name."<br/>".$age."<br/>".$ID."<br/>";
于 2012-06-25T17:43:20.960 回答
1

而不是撇号:

 SELECT Name FROM 'sample_table' LIMIT 0, 30

使用反引号:

 SELECT Name FROM `sample_table` LIMIT 0, 30
于 2012-06-25T17:44:46.907 回答
1

反引号表示数据库、表或列名。单引号向 MySQL 指示字段值。所以它试图将“sample_table”解释为字段值,而不是表名,与“Name”相同,更改为“Name”。

更正的脚本;

$connect = mysql_connect("localhost", "root", "");
if (!$connect) {
    die('Not connected : ' . mysql_error());
}

//Connect to DB
$db_selected = mysql_select_db("testing", $connect);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$sql = "SELECT `Name` FROM `sample_table` LIMIT 0, 30 ";

//Query DB table
$sqlQuery = mysql_query($sql, $connect);
if (!$sqlQuery) {
    die('Invalid query: ' . mysql_error());
}

//fetch the results / convert the results into an array
while($rows = mysql_fetch_array($sqlquery, MYSQL_NUM)) //this is happening
{   
    $name = $rows['name'];
    $age = $rows['age'];
    $ID = $rows['ID'];

    echo ($name."<br />".$age."<br />".$ID."<br />"); 
/*proper echo and html syntax, remember echo is still a function that you are passing a parameter to!*/
}
于 2012-06-25T17:51:27.663 回答
0

尝试删除 sql 语句中的引号:

$sql = "SELECT Name FROM sample_table LIMIT 0, 30";
于 2012-06-25T17:41:28.440 回答