从数据库读取数据得到错误

时间:2016-03-22 22:16:30

标签: php mysql sql

此代码从数据库中读取数据,其中我有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  

表格cm

course foreign key
module  foreign key
num    

表格模块

id      primary key
title       
level 
credits       
school  

1 个答案:

答案 0 :(得分:2)

您的值$_REQUEST['ide']包含非数字字符。因此,where子句

WHERE module = $i

扩展为类似

WHERE module = SCQF07

并且MySQL将未加引号的字符串SCQF07解释为列名。你需要

  1. 将您的查询更改为

    $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'"
    
  2. (请注意$i周围的单引号)或

    1. 切换到使用预处理语句,该语句自动处理引用,转义和类型匹配,并提供针对SQL injection attacks的保护措施。
    2. 要检索结果的所有行,您需要重复调​​用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
          }
      ?>