简体   繁体   中英

Using a join with an SQL query

I would like to query only the data I want from my database using a join. Yet, I am having trouble getting my query to work.

Here is my code. Take a look,

<?php 

$user_id= $_COOKIE['user_id'];

$dbc= mysqli_connect('localhost', 'root', '', 'beta');
$query=" SELECT * FROM posts LEFT JOIN relationships ON (posts.user_id=    
relationship.user_2 AND relationships.user_1 = $user_id AND relationship.status = 4 OR         
3 OR 1)";
$result= mysqli_query($dbc, $query);

echo mysqli_num_rows($result);

?>

I am only trying to see if the query works at this point, by seeing if it returns any rows. But It won't work. What could I be doing wrong?

Your OR in the WHERE clause condition is not in the correct syntax. try something like this:

SELECT  * 
FROM    posts a 
            LEFT JOIN relationships b
                ON a.user_id = b.user_2 
WHERE   b.user_1 = $user_id AND 
        b.status IN (1,3,4)

I suggest that you use PDO or MYSQLi extensions.

In PDO, it could look like this:

<?php
$stmt = $dbh->prepare("SELECT   * 
                      FROM  posts a 
                           LEFT JOIN relationships b
                                ON a.user_id = b.user_2 
                     WHERE  b.user_1 = ? AND 
                            b.status IN (1,3,4)");

$stmt->bindParam(1, $user_id);
$stmt->execute();

?>

Remember to always filter your inputs especially it is used querying your database.

您在查询中混用了“关系”和“关系”,也许坚持使用表的名称是什么?

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