开发者

Building a query string based on variable values. Where is the mistake?

开发者 https://www.devze.com 2023-04-08 19:55 出处:网络
I am trying to create a query string based on GET values passed to common vars: if isset, gTipo = $_GET[\'tipo\'] and others like this.

I am trying to create a query string based on GET values passed to common vars:

if isset, gTipo = $_GET['tipo'] and others like this.

So, here is the code that is not working:

$sqlLista   =   'SELECT * FROM produtos';


if($gTipo <> 0 || $gLinha <> 0)
{
    if($gtipo <> 0 && $开发者_Python百科gLinha == 0 )
    {
        $sqlLista .= ' WHERE id_tipo = '.$gTipo.'';
    }
    if($gtipo <> 0 && $gLinha <> 0)
    {
        $sqlLista .= ' WHERE id_tipo = '.$gTipo.' AND id_linha = '.$gLinha.'';
    }
    if($gTipo == 0 && $gLinha <> 0)
    {
        $sqlLista .= ' WHERE id_linha = '.$gLinha.'';
    }
}

If i set my url as ?tipo=2&linha=4 , my script capture this GET vars and create the common var gTipo and gLinha. If any of this GET are not set, the gTipo or gLinha receive the '0' (zero) value.

When I run the script of query building, nothing is concatened to $sqlLista, except what is done outside the if ( $sqlLista = 'SELECT * FROM produtos'; ).

I am sure this must be a stupid thing that I cannot see. Please, help me =)


I think your problem is variable case:

if($gtipo <> 0...

should be

if($gTipo <> 0...

in 2 places.


dunno what's your problem but the code seems a bit bloated to me
I'd make it this way

$w = array();
$where = '';
if (!empty($_GET['tipo'])) $w[] = 'id_tipo = '.intval($_GET['tipo']);
if (!empty($_GET['linha'])) $w[] = 'id_linha = '.intval($_GET['linha']);
if ($w) $where = " WHERE ".implode(' AND ',$w);
$sqlLista = SELECT * FROM produtos'.$where;

hope you know what you're doing and you really need AND, not OR in the query.

if you have your validations already, the code would be even shorter

$w = array();
$where = '';
if ($gtipo) $w[] = "id_tipo = $gtipo";
if (gLlinha) $w[] = "id_linha = gLinha";
if ($w) $where = " WHERE ".implode(' AND ',$w);
$sqlLista = 'SELECT * FROM produtos'.$where;


Your variable names are inconsistent - $gTipo vs $gtipo.

This line will prevent your inner logic from executing. remove it.

if($gTipo <> 0 || $gLinha <> 0)

As a matter of style, you should use "else if" to prevent multiple "WHERE" lines from being appended if you make a logic error.

0

精彩评论

暂无评论...
验证码 换一张
取 消