Hi I am fairly new at PHP and I am trying to join 2 table and echo the result in and HTML table.
The 2 tables are “client” and “job” I want to echo the clients name using the clients id stored in in the job table with the column name “client_id”. Here’s my code not sure what I am doing wrong. Thanks for the help. I am open to better ways of doing this.
$result = mysql_query("SELECT `id`, `job_name`, `client.id`, `job_day`, `s_t`, `e_t`, `status` FROM job LEFT JOIN client ON job.client_id = client.id");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table class='table table-bordered table-striped mb-none' id='datatable-tabletools' data-swf-path='assets/vendor/jquery-datatables/extras/TableTools/swf/copy_csv_xls_pdf.swf' >";
// printing table headers
echo "<thead>";
echo "<th>#</th>";
echo "<th>Job Name</th>";
echo "<th>Client Name</th>";
echo "<th>Job Day</th>";
echo "<th>Start Time</th>";
echo "<th>End Time</th>";
echo "<th>Status</th>";
echo "</thead>";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tbody>";
echo "<tr>";
echo "<td><a href='job_view.php?job=" . $row['0'] . "'>See</a></td>";
echo "<td>$row[1]</td>";
echo "<td>$row[2]</td>";
echo "<td>$row[3]</td>";
echo "<td>$row[4]</td>";
echo "<td>$row[5]</td>";
echo "<td>$row[6]</td>";
echo "</tr>";
echo "</tbody>";
}
mysql_free_result($result);
?>
</table>
</div>
</section>
You need to put parenthesis around your ON
clause, and specify ambiguous columns (for sure id
, could be others as well), and you need to put backticks around both the table and the column name, individually (not client.id
but client
.id
):
SELECT `job`.`id`, `job_name`, `client`.`id`, `job_day`, `s_t`, `e_t`, `status`
FROM job
LEFT JOIN client ON (job.client_id = client.id)
SELECT `id`, `job_name`, `client`.`id`, `job_day`, `s_t`, `e_t`, `status` FROM job LEFT JOIN client ON job.client_id = client.id
Instead of selecting client
.id
, why don't you select client
.name
or whatever the column name is.