How to get data from two tables in mysql database using php?

by dalton_moen , in category: PHP General , a year ago

How to get data from two tables in mysql database using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , a year ago

@dalton_moen 

To get data from two tables in a MySQL database using PHP, you can use a SQL query that joins the two tables based on a common column. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
// Connect to the database
$host = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database_name';

$connection = mysqli_connect($host, $username, $password, $database);

if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// SQL query to get data from two tables
$sql = "SELECT table1.column1, table1.column2, table2.column1
        FROM table1
        JOIN table2 ON table1.common_column = table2.common_column";

$result = mysqli_query($connection, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. " - Column3: " . $row["column3"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($connection);
?>


In this example, replace table1, table2, column1, column2, column3, and common_column with the actual table and column names in your database that you want to retrieve data from. The common_column is the column that is shared between the two tables.


The SQL query uses a JOIN clause to combine the data from both tables based on the common column. The result set is then fetched using the mysqli_fetch_assoc() function and displayed on the page.

Related Threads:

How to select rows from two tables using mysql?
How to join and get data from two tables in laravel?
How to query data from many tables using union in mysql?
How to store array data in mysql database using laravel?
How to get data from a database using foreach in laravel?
How to combine two mysql tables in node.js?