What is the purpose of using INNER JOIN in PHP when working with MySQL databases?
When working with MySQL databases in PHP, using INNER JOIN allows you to combine rows from two or more tables based on a related column between them. This is useful when you need to retrieve data from multiple tables that are connected by a common key, such as a foreign key relationship. INNER JOIN helps to eliminate rows that do not have a match in both tables, resulting in a more precise and targeted query result.
<?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
INNER JOIN table2 ON table1.id = table2.table1_id";
$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();
?>
Keywords
Related Questions
- What are common mistakes made when using ".include()." to include text in PHP?
- How can PHP developers ensure that their code is following the latest security standards when handling database interactions?
- What are the best practices for using preg_match_all in PHP to search for specific numbers within a string?