php - How do I get data from another table in MySQL?

I'm currently trying to link some databases up for a project I'm working on for my business. Here's my below SQL I'm using for my PHP website.
$sql = "SELECT lname, fname, designation, agency, mobile, direct, email FROM contacts";
$result = $conn->query($sql);
At the moment my output goes like this to show what's in each row using e.g.$lname=$lname["variable"]
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
/* Print the row */
echo "<tr>"."<td>". $lname . "</td><td>" . $fname . "</td><td>" . $designation . "</td><td>" . $agency . "</td><td>" . $mobile . "</td><td>" . $direct . "</td><td><a href='mailto:" . $email . "''>". $email. "</a><br>";
}
}
I have another "clients" table, where each agency has an id - one that matches with $agency at this point. What I want to do is post the corresponding companyname column to that id.
How would I modify my code to do so (and access the column/rows from the secondary table)?
Answer
Solution:
If I've understood the question correctly, the answer should look something like
SELECT ct.lname, ct.fname, ct.designation, ct.agency, ct.mobile,
ct.direct, ct.email, cl.company_name
FROM contacts ct
JOIN clients cl ON ct.agency = cl.id
The crux of it is the SQL JOIN clause.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.