Allysha April
Allysha April

Reputation: 23

How do I echo an inner join column name

I have two tables that I have inner joined called milk and jan both has a column named id. trying to make a modal popup, but it wouldn't work bc of the ambigous id column name so i tried milk.id but still wouldn't work. is there a way around it?

this is my php query:

$sql="SELECT milk.pemohon, milk.nokp, milk.keterangan, jan.status 
FROM milk 
INNER JOIN jan ON milk.id = jan.users_id";

$result = mysqli_query($con,$sql);
    ?>

    <table>
      <thead>
        <tr>
          <th>Pemohon</th>
          <th>No. KP</th>
          <th>Keterangan</th>
          <th>Status</th>
          <th>Penghantaran</th>
        </tr>
      </thead>
      <tbody>
        <?php
        while($row=mysqli_fetch_array($result)) {
        ?>
        <tr>
          <td><?php echo $row["pemohon"]; ?></td>
          <td><?php echo $row["nokp"]; ?></td>
          <td><?php echo $row["keterangan"]; ?></td>
          <td><?php echo $row["status"]; ?></td>
          <td><button data-id='<?php echo $row['milk.id']; ?>' class="userinfo btn btn-success">Info</button></td>
        </tr>
        <?php  
          }
        }  
        ?>
      </tbody>
    </table>

Upvotes: 0

Views: 427

Answers (1)

Firewizz
Firewizz

Reputation: 813

$sql="
SELECT 
    milk.id AS milk_id, 
    milk.pemohon, 
    milk.nokp, 
    milk.keterangan,
    jan.id AS jan_id, 
    jan.status 
FROM milk 
INNER JOIN jan ON milk.id = jan.users_id
";

Now you can just select milk_id or jan_id in php using $row['milk_id'] or $row['jan_id']

To explain: MySQL uses the column name as name, thus on milk.id it uses id. If you have multiple select with the same column name, ex milk.id and jan.id it returns id and id(1) respectively. Best thing is to use an alias with AS followed by the name. In this way, MySQL returns that as the name.

Upvotes: 2

Related Questions