首页 > 解决方案 > PHP/MySQL:根据用户 ID 显示来自不同表的数据

问题描述

我有两张桌子"personal_trainer""training_plan". PersonalTrainerID 是 training_plan 中的外键。我想显示,当培训师使用他们的电子邮件和密码登录时,只显示适用于该 ID 的培训计划。

但是,我无法理解逻辑。我已经对其进行了编码,以便显示 training_plan 表中的所有信息,但我无法创建它以便只有应用于 ID 的行对用户可见。我通过简单的 sql 语句做到了这一点"SELECT * from training_plan"。如果您想知道,有一个过滤器文本框可以搜索不会影响代码的表格。

我已经评论了代码以使其更容易理解。任何帮助将不胜感激!

           <?php
       if (isset($_POST['search'])) /*This code allows the filter textbox to search the db */
       {
           $valueToSearch = $_POST['ValueToSearch'];
           $query = "select * from training_plan WHERE concat('trainingPlanID', `personalTrainerID`, `clientID`, `trainingType`, `exercise1`, `exercise2`, `exercise3`, `exercise4`, `exercise5`, `exercise6`, 'reps', 'sets', 'description')like'%".$valueToSearch."%'";
           $search_result = filterTable($query);

       }
       else {
           $query = "SELECT * from training_plan WHERE PersonalTrainerID= (SELECT personalTrainerID FROM personal_trainer WHERE email=$_SESSION['user'])"; /*The error that is displayed is 'syntax error, unexpected string after ['*/
           $search_result = filterTable($query);
       }

       function filterTable($query)
       {
           $connect = mysqli_connect("localhost:3308","root","","fypdatabase");
           $filter_Result = mysqli_query($connect, $query);
           return $filter_Result;
       }
       ?>



       <?php /*This displays the data in a table but so far outputs all of the table data */
       while($row = mysqli_fetch_array($search_result))
    {
        ?>
                <tr>
                <td><?php echo $row["trainingPlanID"]; ?></td>
                <td><?php echo $row["personalTrainerID"]; ?></td>
                <td><?php echo $row["clientID"]; ?></td>
                <td><?php echo $row["trainingType"]; ?></td>
                <td><?php echo $row["exercise1"]; ?></td>
                <td><?php echo $row["exercise2"]; ?></td>
                <td><?php echo $row["exercise3"]; ?></td>
                <td><?php echo $row["exercise4"]; ?></td>
                <td><?php echo $row["exercise5"]; ?></td>
                <td><?php echo $row["exercise6"]; ?></td>
                <td><?php echo $row["reps"]; ?></td>
                <td><?php echo $row["sets"]; ?></td>
                <td><?php echo $row["description"]; ?></td>
                <td>
                    <a href="?Delete=<?php echo $row["trainingPlanID"]; ?>" onclick="return confirm('Are you sure?');">Delete</a>
                </td>
                <td>
                    <a href="updateTplan.php?Edit=<?php echo $row["trainingPlanID"]; ?>" onclick="return confirm('Are you sure?');">Update</a>
                </td>
              </tr>
              <?php 

标签: phpmysqlsql

解决方案


将您的查询更改为:

$query = "SELECT * from training_plan WHERE PersonalTrainerID = (SELECT personalTrainerID FROM personal_trainer WHERE email='".$_SESSION['user']."')";

推荐阅读