Jump to content

List option in sql query


haribo83

Recommended Posts

I have a list that passes values to an sql statement to show relevant results.

 

I have three options (All, Option One, Option Two) and cannot get the query to work.

 

If I choose option one or option two then the results are fine but I cannot find a way to display all results.

 

The code is below:

 

SELECT * from details WHERE otype = '$listoption'

 

Any help would be great.

Link to comment
https://forums.phpfreaks.com/topic/208577-list-option-in-sql-query/
Share on other sites

Have solved it

 

I assigned the All in the list a value of 0 - don't know if it is best practice but have done the following:

 

if ( $listoption == 0 ) {

$query = "SELECT * from details";;

} else {

$query = "SELECT * from details WHERE otype = '$listoption'";;

}

Heh...I was in the posting this reply just as you posted...

 

I'm not sure I understand the scenario correctly, but I'll suggest code that is structured like this:

 

if ($listoption == ALL)

{

    Execute "SELECT * FROM details"

}

else

{

    Execute "SELECT * FROM details WHERE otype = $listoption"

}

 

If that's not what you are looking for, post your relevant PHP code and describe in a bit more detail what isn't working...I'll look again.

 

As a side note, I would avoid code that concatenates SQL with user input (but maybe you're just writing abbreviated code like I am and you're using parameterized queries in your real code). I have a blog post on this topic: http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx

 

-Brian

If the selection returns a value from a select box or something similar, if you just send back an id and then map those ids to a particular value to add to your query, you should be  safe.  Or as Brian said ... use parameters.

 

$query = 'SELECT * FROM `details` ';
switch ( $listoption )
{
    case 1:
        $query .= 'WHERE otype = \'bugger\' ';
        break;
    case 2:
        $query .= 'WHERE otype = \'booger\' ';
        break;
    default:
      /* Do nothing (ALL) */
}

/* Execute $query */

 

~juddster

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.