IF comparing with GET does not work [closed]

0

Hello. I'm trying to make a comparison in PHP and the IF does not work for nothing. I've tried it in many ways and it did not work.

The code is:

        if(($_GET['categoria']) == 0) {
    $mysql = new conexao();
    echo 'Erro';
    }else{
    $mysql = new conexao();
    $result = $mysql->sql_query("select * from TB_GALERIA where CATEGORIA=".$_GET['categoria']." ");
    while ($row = mysql_fetch_assoc($result)) {
            echo '<div class="item">';
            echo '<a class="item-hover" href="../../../uploads/midia/15989/maior_maior_DSC_0108.jpg">';
            echo '<img src="images/'.$row["IMAGEM"].'" alt="imagem galeria" class="img-responsive lazyOwl" data-src="/images/';
            echo $row["IMAGEM"];
            echo '">';
            echo '</a>';
            echo '</div>';

        }
    }

What's wrong with if? Thanks!

    
asked by anonymous 05.02.2017 / 14:03

3 answers

2

First, before accessing a value within $ _GET it is best to check if the value exists by using isset .

Second, compare with three equal signs "===", because so you compare the value and type, because "false == 0" is true, but "false === 0" is false:

if( isset($_GET['categoria']) )
{
    if( $_GET['categoria'] === 0 )
    {
        // faz tudo que tem que fazer...
    }
}

To see what's inside $ _GET, I suggest doing the following:

echo "<pre>";
var_dump($_GET);
echo "</pre>";

die(); // pra não continuar o script, e você focar no $_GET

If the comparison is not resulting in something expected, then the value of $ _GET was not filled as it should.

    
05.02.2017 / 14:16
1

If you call only the script, without passing any value in the parameters it will always be equal to 0, in this case you should first check if it was passed using

    if ( ! isset( $_GET[ 'categoria' ] ) {
            echo 'Faltou a categoria';
            exit;
    }

    if ( $_GET[ 'categoria' ] == 0 ) {
            // ...
    } else {
            // ...
    }

I think this is it!

    
05.02.2017 / 14:23
0

If you want to keep the same way you are making the mistake is in the relatives you put in if. Below is the correction.

if($_GET['categoria'] == 0) {
$mysql = new conexao();
echo 'Erro';
}else{
$mysql = new conexao();
$result = $mysql->sql_query("select * from TB_GALERIA where CATEGORIA=".$_GET['categoria']." ");
while ($row = mysql_fetch_assoc($result)) {
        echo '<div class="item">';
        echo '<a class="item-hover" href="../../../uploads/midia/15989/maior_maior_DSC_0108.jpg">';
        echo '<img src="images/'.$row["IMAGEM"].'" alt="imagem galeria" class="img-responsive lazyOwl" data-src="/images/';
        echo $row["IMAGEM"];
        echo '">';
        echo '</a>';
        echo '</div>';

    }
}
    
05.02.2017 / 15:16