这段代码从数据库中读取数据,我有 3 个表格,我想尝试打印模块表中的课程标题及其详细信息,但我收到错误,说"where 子句"中的未知列"SCQF07"可以给我建议如何解决这个问题,提前谢谢
<?php
$m = new mysqli("localhost","user","pwd","courses");
if ($m->connect_errno)
{
die("Database connection failed");
}
$m->set_charset('utf8');
$i = $_REQUEST['ide'];
$sql = "SELECT module.level, module.credits, cm.course, module.school, course.title
from cm
join module on (module = module.id)
join course on (course = course.id)
where module = $i";
$res = $m->query($sql) or die($m->error);
$CastArray = Array();
$row = $res->fetch_assoc();
?>
<html>
<head>
</head>
<body>
<h1><?php echo "$row[tile] - <a href=movies3.php?ide=$row[course]>$row[title]</a>"; ?></h1>
</body>
</html>
表课程
id primary key
title
href
level
award
summary
dept
subject
overview
wyl
careers
表 厘米
course foreign key
module foreign key
num
表模块
id primary key
title
level
credits
school
您的值$_REQUEST['ide']
包含非数字字符。因此,where 子句
WHERE module = $i
扩展为类似
WHERE module = SCQF07
MySQL将不带引号的字符串SCQF07
解释为列名。您需要
将查询更改为
$sql = "SELECT module.level, module.credits, cm.course, module.school, course.title from cm join module on (module = module.id) join course on (course = course.id) where module = '$i'"
(注意$i
两边的单引号),或
- 切换到使用预准备语句,它自动处理引号、转义和类型匹配,并提供针对 SQL 注入攻击的保护措施。
若要检索结果的所有行,需要重复调用fetch
。这通常在while
循环中完成,如下所示:
<?php
$res = $m->query($sql) or die($m->error);
$CastArray = Array();
while ($row = $res->fetch_assoc())
{
?>
<h1><?php echo "{$row['title']} - <a href=movies3.php?ide={$row['course']}>{$row['title']}</a>"; ?></h1>
<?php
}
?>