Nukhba Arshad Nukhba Arshad - 3 months ago 19
PHP Question

sql query to fetch data of a particular user, from three tables

One is a user table.
Second is a places table.
third is favorites table (having two fk one from user and other from places)
now I want to get all the favorite places of one user, how do I do that?

I tried to play aroung with joins but what I don't know is how to get data of a particular user.
$qry =

"SELECT places.place_id , places.db_image ,places.description from places
inner join favorites on places.place_id = favorites.place_id
inner join user on user.id = favorites.user_id
";

$query=mysqli_query($con ,$qry);
$return_arr = array();

Answer
$sql = sprintf(
'SELECT
  p.place_id,
  p.db_image,
  p.description
FROM
  places p INNER JOIN
  favorites f ON p.place_id = f.place_id INNER JOIN
  user u ON u.id = f.user_id
WHERE
  u.id = %d'
, $userId);

or if you want simply select all columns from places

SELECT
  p.*
FROM
  places p INNER JOIN
  favorites f ON p.place_id = f.place_id INNER JOIN
  user u ON u.id = f.user_id
WHERE
  u.id = %d

It is better to use prepared statements, but if you are not familiar with them, this is good enough.