Cheers,
I have 4 tables:
DIRECTORY - iddir, idcust, idfile
CUSTOMERS - id_cust, fname, lname
FILES - idf, id_dir, id_type
TYPEF - idtype, type_name
Basically, I want to display all values like this:
ID DIR, CUST FNAME, CUST LNAME, Name of the file
I have tried with this SQL query:
SELECT * FROM directory
JOIN customers ON idcust = id_cust
JOIN files ON idfile = idf AND
JOIN typef ON id_type = idtype
Everything works until the last JOIN. Without it, I don't have any error, but I can't print the name of the file type which corresponds to the id of the file.
I searched, I have tried some options, but nothing worked. How can I bring to the parent table a piece of information from the "grandson table"? Thank you
PHP code
$conn = mysqli_connect("localhost", "root", "", "demodb");
if ($conn -> connect_error){
die("Connection failed:". $conn-> connect_error);
}
$sql = "SELECT * FROM directory
JOIN customers ON idcust = id_cust
JOIN files ON idfile = idf AND
JOIN typef ON id_type = idtype";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["iddir"] ." </td>
<td>". $row["fname"] ." </td>
<td>". $row["lname"] ." </td>
<td>". $row["id_type"] ." </td>
<td> ". $row["type_name"] ." </td>
</tr>";
}
echo " </table>";
} else {
echo "0 result";
}
$conn->close();
I hope this will work for you
$conn = mysqli_connect("localhost", "root", "", "demodb");
if ($conn -> connect_error){
die("Connection failed:". $conn-> connect_error);
}
$sql = "SELECT d.iddir, c.fname, c.lname, f.id_type, t.type_name
FROM directory AS d
LEFT JOIN customers AS c ON d.idcust = c.id_cust
LEFT JOIN files AS f ON d.idfile = f.idf
LEFT JOIN typef AS t ON f.id_type = d.idtype";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["iddir"] ." </td>
<td>". $row["fname"] ." </td>
<td>". $row["lname"] ." </td>
<td>". $row["id_type"] ." </td>
<td> ". $row["type_name"] ." </td>
</tr>";
}
echo " </table>";
} else {
echo "0 result";
}
$conn->close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.