2013-03-05 106 views
0

這是MySQL的代碼我嘗試運行:MySQL查詢錯誤SQL語法PDO

SELECT i.id, i.courseid, i.title, i.info, i.lasteditedby, u.id, u.forename, u.surname 
FROM courseinformation as i JOIN users AS u ON (i.lasteditedby = u.id) 
WHERE i.courseid = :courseid 
ORDER BY i.id desc LIMIT 2; 

即時得到這個錯誤:

/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':courseid ORDER BY i.id desc LIMIT 2' at line 1 */ 

我的目標是獲得ID,courseid,標題,信息,從CourseInformation表中繼承,然後從用戶表中獲取Id,forename和surname。用戶標識與lastededby相同。

我還真看不出來,因爲我已經使用

:courseid 
其他PDO SQL querys

是香港專業教育學院運行


參考什麼SQL語法錯了,這是我的PHP代碼與該SQL在

 $courseid = 'G11111'; 
     $sql = "SELECT i.id, i.courseid, i.title, i.info, i.lasteditedby, u.id, u.forename, u.surname FROM courseinformation as i JOIN users AS u ON (i.lasteditedby = u.id) WHERE i.courseid = :courseid ORDER BY i.id desc LIMIT 2"; 
     $sql->bindParam(":courseid", $courseid); 
        $sql->execute(); 

     foreach ($db->query($sql) as $row) { 
      echo '<div class="announceTitle">'; 
      echo $row['title'].'<br />'; 
      echo $row['forename'].' '.$row['surname'].'<br />'; 
      echo '</div> 
       <div class="announceText">'; 
      echo $row['info']; 
      echo '</div> 
       <br /> 
       <br />'; 
     } 

任何人都可以請指出我的方向,以什麼是錯的? 感謝您的閱讀

+2

我不明白..'$ sql'是一個字符串,所以調用'bindParam'就應該給一個致命的PHP錯誤 – 2013-03-05 20:44:22

回答

0

您還沒有創建語句句柄,您已經創建了一個字符串。

tutorial建議如下:

$sth = $db->prepare("SELECT i.id, i.courseid, i.title, i.info, i.lasteditedby, u.id, u.forename, u.surname FROM courseinformation as i JOIN users AS u ON (i.lasteditedby = u.id) WHERE i.courseid = :courseid ORDER BY i.id desc LIMIT 2"); 
$sth->bindParam(":courseid", $courseid); 

以後你$db->query執行這個字符串就是錯誤的結果哪裏,是你可能需要更好的例子從工作的標誌,因爲這似乎是一個幾矛盾的技術被同時應用。

+0

謝謝你這麼多!並感謝該教程:) – user1842842 2013-03-05 21:12:39