Help with SELECT returns

Asked

Viewed 37 times

1

The SELECT below when run directly in Phpmyadmin, returns all the results I want, but when I use in PHP function it comes empty:

$user = $_SESSION["usuario"]["id"];
$sel = BD::conn()->prepare("SELECT lk.*, ep.*
                                    FROM gostados lk
                                    INNER JOIN episodios ep ON 
                                        ep.id_anime = lk.id_anime AND
                                        ep.ep_temporada = lk.ep_temporada AND
                                        ep.episodio = lk.episodio
                                    WHERE 
                                        lk.id_usuario = :user  
                                    ORDER BY data ASC
                                        LIMIT 0,200");

$sel->bindValue(":user", $user);
$sel->execute();
$row = $sel->rowCount();
if($row >= 1){
    echo "1";
}else{
    echo "0";
}

I already checked the id of the user being used as bindValue and it’s right, what could be the mistake that makes the $row always return 0?

1 answer

2


Probably your problem is in Inner Join,

Switch to Left Join and see if it’s coming from the other table. Ex:

$user = $_SESSION["usuario"]["id"];
$sel = BD::conn()->prepare("SELECT lk.*, ep.*
                                    FROM gostados lk
                                    LEFT JOIN episodios ep ON 
                                        ep.id_anime = lk.id_anime AND
                                        ep.ep_temporada = lk.ep_temporada AND
                                        ep.episodio = lk.episodio
                                    WHERE 
                                        lk.id_usuario = :user  
                                    ORDER BY data ASC
                                        LIMIT 0,200");

$sel->bindValue(":user", $user);
$sel->execute();
$row = $sel->rowCount();
if($row >= 1){
    echo "1";
}else{
    echo "0";
}

Explanation:

The Inner Join will make that only bring record when he find the associations of the other table, if there is something in the table episodios that connect on the line you want it will not bring, already the left Join will bring anyway, provided you have in the first table the "liked"

  • 1

    I just found the real root of the problem here while reading your code, the problem is in ORDER BY data, which should actually be Lk.data, but thank you so much for the tip from LEFT JOIN did not know it worked like this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.