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
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'";;

}

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.