-1

I'm trying show some records from table and if doesn't exist to show button create new. If exist to show record.

There are two tables - users

user_id
username
...

And restaurants

rest_id
name
menu

So after user is created and he log into his account must have condition if user_id has restaurant user_id = menu (menu from restaurants). If doesn't exist in restaurant show button create. This is the query with which I trying

$q = $pdo->prepare("SELECT * FROM restaurants m                 
          LEFT JOIN users ON users.user_id = m.menu WHERE rest_id = :user_id");

                $q->bindParam(':user_id', $_SESSION['user_id']);
                $q->execute();
                // fetch the results
                $results = $q->fetchAll(PDO::FETCH_ASSOC);
                if(count($results) > 0) {
                    foreach($results as $res) {
                        echo '<a href="users/restaurant.php?rest_id='. $res['rest_id'] .'"> '.$res['name'].' </a>';
                    }
                } else {
                        echo '<a href="users/restAdd.php?rest_id='.$_SESSION['user_id'].'">Create New</a>';
                }

In this way when user login he see button Create New because he doesn't have one. The problem is when he log again after he is created record already ... button Create New is visible again.

I thing the problem is in the query or no?

UPDATE: menu row hold user_id from session when he create new one. This is in restAdd.php

    $sql = "INSERT INTO restaurants ( name, menu, image) VALUE ( :name, :menu, :image)";
                    $q = $pdo->prepare($sql);
                $q->execute(array(
                ':name'     => $name,
                ':menu'     => $_SESSION['user_id'],
                ':image'    => $forDB
                ));
Jason Paddle
  • 1,095
  • 1
  • 19
  • 37

2 Answers2

1

Try with this query:

SELECT m.rest_id, m.name FROM restaurants m                 
  INNER JOIN users ON users.user_id = m.menu
  WHERE menu = :user_id

1) INNER JOIN instead of LEFT, you want to check if there are restaurants related with the user.

2)I think you did a little mistake, the menu field is wich contains the user id

javier_domenech
  • 5,995
  • 6
  • 37
  • 59
  • Thank's for your help. I guess I need to learn differences between LEFT, RIGHT, INNER and OUTER joins. – Jason Paddle Jan 13 '15 at 14:48
  • 1
    You're welcome. Here is one of my favourite answers of SO, check it. http://stackoverflow.com/questions/38549/difference-between-inner-and-outer-joins – javier_domenech Jan 13 '15 at 14:52
-1

In this case you need in your where clause menu = :user_id not rest_id = :user_id Try with this:

SELECT * FROM restaurants m                 
    LEFT JOIN users ON users.user_id = m.menu WHERE menu = :user_id"
Goro
  • 499
  • 1
  • 13
  • 31