Jonuux
Jonuux

Reputation: 531

Search with mutiple values in mysql

I'm creating a search script with PHP and MySQL. Right now, I've reached something like this, but in some cases its not working very well:

$id = JRequest::getInt('id');
$catid = JRequest::getVar('catid');     
$console = JRequest::getVar('console'); 
$ram = JRequest::getVar('ram');

if ($ram) {
    $ram = "AND rec_ram='$ram'";
}       

if ($console) {
    $console = "AND console='$console'";
}

$array = array(
    catid => $catid,    
    console => $console,
    ram => $ram,
);

$db = JFactory::getDBO();
$query = "SELECT * FROM #__content WHERE catid='$catid' $array[console] $array[ram]";

What are other alternatives to do this?

Sometimes values could be empty, this is why I use:

if ($console) {
    $console = "AND console='$console'";
}

but its still working bad in some cases.

Upvotes: 1

Views: 78

Answers (1)

ozahorulia
ozahorulia

Reputation: 10084

Use the concatenation! It's very bad to put all variables just into a string.

<?php

    $conditions = '';

    if ($ram) {
        $conditions .= ' AND `rec_ram`="'.$ram.'"';
    }       

    if ($console) {
        $conditions .= ' AND `console`="'.$console.'"';
    }

    $query = 'SELECT * FROM `#__content` WHERE `catid`=' . $catid . $condition . ';';

?>

Note, that if console or rec_ram have type of int, you do not need to quote it's values.

<?php

    // column console is int 
    if ($console) {
        $conditions .= ' AND `console`='.$console;
    }

?>

Okay, here is a way to provide a correct sql structure:

$conditions = array();

if ($ram) {
    $conditions[] = '`rec_ram`="'.$ram.'"';
}

if ($console) {
    $conditions[] = '`console`="'.$console.'"';
}

// some other conditions...

$condition = '';
if (sizeof($conditions) > 0)
    $condition = ' WHERE ' . implode(' AND ', $conditions);

$query = 'SELECT * FROM `#__content`' . $condition . ';';

Upvotes: 1

Related Questions