What is the correct syntax for joining multiple tables in a MySQL query using PHP?
When joining multiple tables in a MySQL query using PHP, you need to specify the table names and the join conditions in the query. This can be done using the JOIN keyword followed by the table name and the ON keyword to specify the join condition. Make sure to also specify the columns you want to select from each table in the SELECT statement.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT table1.column1, table2.column2
FROM table1
JOIN table2 ON table1.common_column = table2.common_column";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- How can PHP be used to validate and format date input from select fields before saving it to a database?
- How can PHP developers ensure consistency and accuracy when working with different date and time formats in their applications?
- How can JSON encoding be used to improve data exchange between PHP and JavaScript in web applications?