SQL语法错误/无效查询 - WAMP,phpMyAdmin

时间:2012-06-25 17:38:45

标签: php mysql sql database phpmyadmin

我在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 Screenshot

5 个答案:

答案 0 :(得分:1)

试试这个

SELECT Name FROM sample_table LIMIT 0, 30 

而不是

SELECT Name FROM 'sample_table' LIMIT 0, 30

答案 1 :(得分:1)

改变这个:

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

进入这个:

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

请注意,我已将'更改为`

顺便说一下,echo语法应如下所示:

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

答案 2 :(得分:1)

而不是撇号:

 SELECT Name FROM 'sample_table' LIMIT 0, 30

使用反引号:

 SELECT Name FROM `sample_table` LIMIT 0, 30

答案 3 :(得分: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!*/
}

答案 4 :(得分:0)

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

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