简体   繁体   English

无法使PDO SQL查询正常工作

[英]Can't get PDO SQL query to work

I can't get this query to work. 我无法使该查询正常工作。 It only shows the first DB entry. 它仅显示第一个数据库条目。 Any ideas greatly appreciated. 任何想法表示赞赏。

/* prepare */ /* 准备 */

$sql = "SELECT personal.firstName, personal.lastName, etc. 
        FROM personal 
        LEFT JOIN exam 
        ON personal.P_ID=exam.P_ID 
        LEFT JOIN contact 
        ON exam.P_ID=contact.P_ID 
        WHERE exam.Level = ? 
        AND exam.Centre!='' ORDER BY exam.Centre";

$stmt = $db->prepare($sql);

/* Execute */ $stmt->execute(array($level)); / *执行* / $ stmt-> execute(array($ level));

/* Fetch */
            $row = $stmt->fetch(PDO::FETCH_ASSOC);    





/*  Display  */
                    echo '<table>
                         <tr>
                    <td>Name</td>
                    <td>Surname</td>
                    <td>Paid?</td>
                    <td>Etc</td>
                    <td>Etc</td>
                    <td>Etc</td>
                        </tr>';

if ($row) { foreach ($row as $key => $value) if($ row){foreach($ row as $ key => $ value)

              {
                echo '<td>';
                echo $value;
                echo '</td>';
            }
               echo '</tr>';
          }
       echo '</table>';

A simple tutorial for you to get it right. 一个简单的教程,供您正确使用。

  1. Take your mysql query that works 以您的mysql查询有效

      $sql = "SELECT * FROM t WHERE a = $a AND b = '$b'"; 
  2. Make sure it works. 确保它可以工作。 If not - make it work first. 如果没有,请先使其工作。
  3. Take out every variable you interpolate in it ( along with all corresponding formatting, including slashes and quotes ), and put a question mark in place of them. 取出您在其中插值的每个变量( 以及所有相应的格式,包括斜杠引号 ),并在其中放置问号。

      $sql = "SELECT * FROM t WHERE a = ? AND b = ?"; 
  4. Move these variables into execute() in the form of array 将这些变量以数组形式移动到execute()

      $sql = "SELECT * FROM t WHERE a = ? AND b = ?"; $stm = $db->prepare($sql); $stm->execute(array($a,$b)); 
  5. Everything works. 一切正常。

  6. If still not - configure your PDO and PHP in order to see errors if any , read the error message and take appropriate action. 如果仍然没有,请配置您的PDO和PHP以查看错误(如果有) ,阅读错误消息并采取适当的措施。

To get your data in the proper format you have to use proper fetch method 要以正确的格式获取数据,必须使用正确的提取方法

     $data = $stm->fetchAll();
     foreach ($data as $row) {
       echo $row['id'];
       // do whatever
     }

Please refer to tag wiki for other methods 其他方法请参考标签维基

I'm new at PDO as well, but from your code I noticed that there is no :centre in the query there, so that parameter won't bind? 我也是PDO的新手,但是从您的代码中,我注意到那里的查询中没有:centre ,因此该参数不会绑定?

Another thing is in WHERE exam.Level:level , are you sure you meant this and not: WHERE exam.Level = :level ? 另一件事是WHERE exam.Level:level ,您确定不是这个意思吗? WHERE exam.Level = :level吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM