简体   繁体   中英

How to JOIN two tables correctly?

Somewhere you have patience for takes you somewhere, only now the last problem.

It works for one party, only for the persons who not have any recipies, the peron with recipies can't see it, it only see a blank ó page.

$usersi = $dbh->prepare('SELECT * FROM recettes WHERE id_user = :id');
$usersi->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$usersi->execute();
$usersis = $usersi->fetchAll(PDO::FETCH_ASSOC);

For a user with id = 1:

<?php
$usersi_sql = $dbh->prepare('SELECT * FROM recettes WHERE id_user = 1');
$usersi_sql->execute();
$usersi = $usersi_sql->fetchAll(PDO::FETCH_ASSOC);
?> 

The solution on my question is:

$usersi_sql = $dbh->prepare('SELECT * FROM recettes WHERE id_user = :id');
$usersi_sql->bindParam(':id', $ma['id'], PDO::PARAM_INT);
$usersi_sql->execute();
$usersi = $usersi_sql->fetchAll(PDO::FETCH_ASSOC);  
if(isset($usersi[0])) {
?>

Here your HTML code

<?php
}
 }else{
?>

Here your HTML else code

<?php } ?>

This in the top of your php file

$ma_sql = $dbh->prepare('SELECT * FROM users WHERE id = :id');
$ma_sql->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$ma_sql->execute();
$ma = $ma_sql->fetch();

I used this in my top because it also check if the user is logged in or not, but this above is a part of that code.

If you want all recepies linked to all users -

SELECT * FROM recettes INNER JOIN users ON recettes.id_user = users.id LIMIT 20

If you want distinct recepies linked to all users -

SELECT DISTINCT recettes.* FROM recettes INNER JOIN users ON recettes.id_user = users.id LIMIT 20

If you want just for one user -

SELECT * FROM recettes WHERE id_user = user LIMIT 20

Change PHP call to -

$usersi_sql->bindParam(':user', $user_id);
$usersi_sql->execute()

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