Oscar ho
Oscar ho

Reputation: 36

using JOIN two table but data did not display

I am using JOIN to join two tables:

   $sql = "SELECT * FROM employee JOIN employee_medical on employee = medical_notes";
   $data = mysql_query($sql , $testing);

and I display the table and the data:

   echo "<table border=2>
    <tr>
   <th>emp_id</th>
   <th>emp_name</th>
   <th>emp_ic</th>
   <th>emp_phone</th>
   <th>emp_address</th>
   <th>medical_notes</th>
   </tr>";


if($data = mysql_query($sql) or die ())
  {

while ( $record = mysql_fetch_array($data))
{

    echo"<tr>";
    echo "<td>" . $record['emp_id'] . "</td>";
    echo "<td>" . $record['emp_name'] . "</td>";
    echo "<td>" . $record['emp_ic'] . "</td>";
    echo "<td>" . $record['emp_phone'] . "</td>";
    echo "<td>" . $record['emp_address']. "</td>";
    echo "<td>" . $record['medical_notes']. "</td>";
    echo "</tr>";
}

};

Is there a problem in my PHP coding? My table is displayed but the data is not.

Upvotes: 1

Views: 287

Answers (2)

Martin
Martin

Reputation: 22760

Fixes and solutions:

  • Use die(":: ".mysql_error($testing)); To output any SQL errors.

  • $data = mysql_query($sql) or die(":: ".mysql_error() ));

  • You need to define the <table>.<columns> in MySQL when you are referencing more than one table, for every single column referenced, Rahul has the correct answer. So:

$sql = "SELECT * FROM employee JOIN employee_medical on employee.employee = employee_medical.medical_notes";

See the <Table>.<column> structure? Always use that.

  • It is very good idea to get into the habit if declaring which type of JOIN you want to use. There are INNER, OUTER and some other Joins, please explore and clarify your code.

  • Update to MySQLi, with your reference already to the connection with $testing you are nearly there! Turn all your MySQL_ commands to mysqli_<whatever>($connection, $querty); (it's a little more complex, but only a little.

  • mysql_fetch_array might not return key values, depending on how your SQL is set up. so if the data does not appear but you're SURE it's there, then try using mysqli_fetch_assoc() instead.

Upvotes: 0

Rahul
Rahul

Reputation: 77866

Not sure if there is any PHP related issue present but your query ON clause is weird. It should rather look like

SELECT e.* 
FROM employee e 
//Provide proper column names on which to join both the table 
JOIN employee_medical em on e.employeeid = em.medical_notes;

Upvotes: 2

Related Questions