Search code examples
phphtmlmysqlforeign-keys

left join query of mysql php


I'm working on a project where I have two tables 1 is the Users table and another one in the Department table. here I have given a foreign key connection to the department table to the user's table and checked that is working fine. (getting data of particular foreign key). now my requirement is in a single table I want to display all users along with that the foreign key value also. here.

require_once "database.php";

$result = "SELECT * FROM Users";
// , Department WHERE Department.Department_ID = Users.Dpt_id
$output = mysqli_query($conn, $result);


<?php
          while ($single = $output->fetch_assoc()):?>
      <tr>
          <td><?php echo $single['firstname']; ?></td>
          <td><?php echo $single['lastname']; ?></td>
          <td><?php echo $single['email']; ?></td>
          <td><?php echo $single['phnumber']; ?></td>
          <td><?php echo $single['provider']; ?></td>
          <td><?php echo $single['location']; ?></td>
          <td><?php echo $single['Dpt_id']; ?>
            


          </td>
          <td><?php if ($single['Dadmin'] == 1){
                echo '<p>Department admin</p>';
            }
            elseif($single['Superuser'] == 1){
              echo '<p>SUPER</p>';
            }
            else{
              echo '<p>USER</p>';
            }

            ?></td>
<?php endwhile ?>

tried code:

$result = "SELECT * FROM Users, Department WHERE 
Department.Department_ID = Users.Dpt_id";
$output = mysqli_query($conn, $result);

so here is my code. please help me to get the value from the foreign key.


Solution

  • I think you want this result but i don't know your column name:

    SELECT u.*, d.department_name
    FROM USERS u
    LEFT JOIN Department d 
    ON u.dpt_id = d.department_id