我刚刚编写了这段代码,它回应了它应该是什么,但是在echo语句之后它给了我错误 -
您的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 {
}
?>
答案 0 :(得分:2)
尝试使用quote包装查询:
$classes = mysql_query("SELECT * FROM classes WHERE class_id = '".$class."'") or die(mysql_error());
或使用PDO完全更改您的查询。因为,不推荐使用mysql_ *函数。
答案 1 :(得分: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 {
}
答案 2 :(得分:-1)
如果$ class为空,则会收到该错误,该错误会使您的查询为SELECT * FROM classes WHERE class_id =
无效。试试引用它。如果你引用它,至少你会得到SELECT * FROM classes WHERE class_id = ''
"SELECT * FROM classes WHERE class_id = '".$class."'";