简体   繁体   中英

How do I add another mysqli query into a while loop?

So I am carrying out a query and returning the results in the form of a table. The code below works well.

        <table>
      <thead>
        <tr style="text-align: center;">
          <th>Activity</th>
          <th>Description</th>
          <th>Frequency</th>
          <th>Mandatory</th>
          <th>Added Yet</th>
        </tr>
      </thead>
      <tbody>
        <?php
          $stmt = $conn->prepare("SELECT * FROM knowledgebase ORDER BY category ASC");
          $stmt->execute();
          $result = $stmt->get_result();
          if($result->num_rows === 0) echo "<tr><td>No activities found</td><td></td><td></td><td></td><td></td><td></td></tr>           </tbody>
                  </table></br></br>
          Why not add your first activity from our <a href=\"#\">Knowledge base</a> or <a href=\"create_activities.php\">create a new activity</a> of your own";
          else {
          while($row = mysqli_fetch_array($result)) {
              $activity_id          =   $row['id'];
              $title                =   $row['title'];
              $description          =   $row['description'];
              $frequency            =   $row['frequency'];
              $mandatory            =   $row['mandatory'];

              echo "<tr><td><a href=\"add_activities.php?id=".$activity_id."\">".$title."</a></td><td>".$description."</td><td style=\"text-align: center;\">".$frequency."</td><td style=\"text-align: center;\">".$mandatory."</td><td></td></tr>";
            }
          }
           $stmt->close();
         ?>
      </tbody>
    </table>

What I want to add in is another query inside the final <td></td> . What I want to do is query a second db table and say if this activity has already been added to the users table, echo YES, otherwise, echo NO .

The problems is, adding the query into the while loop keeps throwing errors.

Any suggestions gratefully received.

Instead of running another query for every row, you could join the users table to the knowledgebase table in your first query. If you use a left join, you'll still get all the rows from knowledgebase.

SELECT knowledgebase.*, userstable.activity_id
FROM knowledgebase
     LEFT JOIN userstable ON knowledgebase.id = userstable.activity_id
ORDER BY category ASC

Then in your last <td> , you can print YES/NO depending on whether or not there was a matching row in the users table.

...<td><?php echo $row['activity_id'] ? 'YES' : 'NO' ?></td>...

(I made up names for your other table and column, but I think it shows the general idea.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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