简体   繁体   中英

MySQL/PHP - Select all the rows where column from table 1 is equal to column from table 2 and creating a foreach loop

I am searching for a way that i can select all the rows from MySQL table where column from table1 is equal to column from table 2.

Here is what i want to achieve describing it by code. I tried this but nothing happens.

SELECT * FROM `table1` WHERE `table1.id`= `table2.id` ORDER by `table1.name` ASC; 

And then when i select these rows i have to echo some of them into foreach loop, something like this:

<?PHP
foreach($results as $row){
echo $row['table1.name'];             
}
?>

Can you give me a correct way to make this thing happen as an answer to my question.

Thanks in advance!

Use both tables in FROM part

SELECT * FROM `table1`, `table2` WHERE `table1.id`= `table2.id` ORDER by `table1.name` ASC;

Or use an INNER JOIN like this

    SELECT * FROM `table1` INNER JOIN `table2` ON `table1.id`= `table2.id` ORDER by `table1.name` ASC

& then fetch values like this, you do not need alias in $row[], but columns (or their respective aliases) must be unique

<?PHP
    $query = "SELECT * FROM `table1`, `table2` WHERE `table1.id`= `table2.id` ORDER by `table1.name` ASC";

    $res = mysqli_query($conn, $query);
    while($row = $mysqli_fetch_assoc($res)){
        echo $row['name'];             
    }
?>

Answer assumes you have created a database connection named $conn

Use mysql join

SELECT * FROM `table1` inner join table2 on `table1.id`= `table2.id` ORDER by `table1.name` ASC;

or full code is

<?PHP
    $query = "SELECT * FROM `table1` inner join table2 on `table1.id`= `table2.id` ORDER by `table1.name` ASC";

    $res = mysqli_query($conn, $query);
    $row = $mysql_fetch_array($res);
    foreach($row as $rows){
    //Add colum name 
    echo $rows['name'];
    }

?>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM