'Select 2 different values from 2 different tables in a single $sql query
I want to select the firstName and lastName from a different table, but im having some issues, I'll paste the code down below.
The table orders does not contain the firstName and lastName, so I want to call firstName and last name from from table users, but I don't know how. I want help with the query!
<?php $sql = "SELECT * from orders";
//In this line above i also want to select firstName and lastName from table users
$result = mysqli_query($conn, $sql);
$counter = 0;
while($row = mysqli_fetch_assoc($result)){
$Id = $row['userId'];
$orderId = $row['orderId'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$zipCode = $row['zipCode'];
$phoneNo = $row['phoneNo'];
$amount = $row['amount'];
$orderDate = $row['orderDate'];
$paymentMode = $row['paymentMode'];
if ($paymentMode == 0) {
$paymentMode = "Cash on Delivery";
} else {
$paymentMode = "Online";
}
$orderStatus = $row['orderStatus'];
$counter++;
echo '<tr>
<td>' . $orderId . '</td>
<td>' . $Id . '</td>
<td>' . $firstName . '</td>
<td>' . $lastName . '</td>
<td data-toggle="tooltip" title="' .$address. '">' . substr($address, 0, 20) . '...</td>
<td>' . $phoneNo . '</td>
<td>' . $amount . '</td>
<td>' . $paymentMode . '</td>
<td>' . $orderDate . '</td>
<td><a href="#" data-toggle="modal" data-target="#orderStatus' . $orderId . '" class="view"><i class="material-icons"></i></a></td>
<td><a href="#" data-toggle="modal" data-target="#orderItem' . $orderId . '" class="view" title="View Details"><i class="material-icons"></i></a></td>
</tr>';
}
if ($counter==0) {
?>
<script>
document.getElementById("NoOrder").innerHTML = '<div class="alert alert-info alert-dismissible fade show" role="alert" style="width:100%"> You have not Recieve any Order! </div>';</script>
<?php`
}
?>
I've tried may query methods but none of them worked so I could need some help from professionals
Solution 1:[1]
Use INNER JOIN,
If your orders table is orders and users table is users.
You can construct a query like below,
SELECT o.*, u.firstName as firstName, u.lastName as lastName FROM orders o INNER JOIN users u ON o.user_id = u.id.
Provided you have user_id column in orders table with value equal to primary key of users table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shoyeb Sheikh |
