3

我刚刚写了这段代码,它回显了它应该做的,但是在回显语句之后它给了我错误-

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

为什么会这样?我如何解决它?

<?php
$myclasses = explode(',', $_SESSION['classlist']);  
$theirclasses = explode(',', $user_info['classlist']);
$common_classes = array_intersect($myclasses, $theirclasses);

if (count($common_classes) > 0) {     

    foreach ($common_classes as $class) {
        $classes = mysql_query("SELECT * FROM classes WHERE class_id = ".$class) or die(mysql_error());
        while($currentRow = mysql_fetch_array($classes)){
        echo $currentRow['class_name'];
        }
    }  
}
else {
}

?>
4

3 回答 3

2

尝试用引号包装您的查询:

$classes = mysql_query("SELECT * FROM classes WHERE class_id = '".$class."'") or die(mysql_error());

或使用PDO完全更改您的查询。因为, mysql_* 函数已被弃用。

于 2012-11-23T23:35:32.100 回答
0

我将假设 $class 变量在传递给查询时出现问题。在这种情况下,我通常做的是将 SQL 查询分配给一个字符串变量并将其转储以立即测试整个查询。帮助我找出 SQL 语法错误或是否有任何不需要的字符。

<?php
$myclasses = explode(',', $_SESSION['classlist']);  
$theirclasses = explode(',', $user_info['classlist']);
$common_classes = array_intersect($myclasses, $theirclasses);

if (count($common_classes) > 0) {     

    foreach ($common_classes as $class) {
        $sql = "SELECT * FROM classes WHERE class_id = '{$class}'" ; // use {} inside double quotes
        var_dump($sql); // check out the what the query becomes 
        $classes = mysql_query($sql) or die(mysql_error());
        while($currentRow = mysql_fetch_array($classes)){
        echo $currentRow['class_name'];
        }
    }  
}
else {
}
于 2012-11-23T23:40:30.980 回答
-1

如果 $class 为空,您将收到该错误,这将使您的查询SELECT * FROM classes WHERE class_id =无效。尝试引用它。如果你引用它,至少你会得到SELECT * FROM classes WHERE class_id = ''

"SELECT * FROM classes WHERE class_id = '".$class."'";
于 2012-11-23T23:36:44.273 回答