Author Topic: List option in sql query  (Read 888 times)

0 Members and 1 Guest are viewing this topic.

Offline haribo83Topic starter

  • Irregular
  • Posts: 2
    • View Profile
List option in sql query
« on: July 22, 2010, 03:30:02 PM »
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.

Offline haribo83Topic starter

  • Irregular
  • Posts: 2
    • View Profile
Re: List option in sql query
« Reply #1 on: July 22, 2010, 05:06:18 PM »
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'";;
}

Offline Brian Swan

  • Irregular
  • Posts: 47
    • View Profile
Re: List option in sql query
« Reply #2 on: July 22, 2010, 05:14:49 PM »
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

Offline awjudd

  • Guru
  • Enthusiast
  • *
  • Posts: 326
    • View Profile
Re: List option in sql query
« Reply #3 on: July 25, 2010, 02:37:39 PM »
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
The law of everything: Garbage in, Garbage out.

If you don't give us enough information to help you the correct way, the results won't end up being correct.