PHP / MySQL:根据用户ID显示来自不同表的数据

时间:2019-01-02 10:39:41

标签: php mysql sql

我有两个表"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 

1 个答案:

答案 0 :(得分:1)

将查询更改为:

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