views:

41

answers:

4

I have a fairly simple question I'm guessing. I have the following code at the beginning of my function, but it must not be correct because it causes the blank to turn blank. If I comment out the IF statement, everything runs fine.

What am I doing wrong?

Sorry, it's probably very basic...

function get_entries($order = 'newest', $slug = null) {

        $wheresql = '';
        if (isset($slug)) {  
            $wheresql = 'WHERE entries.category_id = (SELECT categories.category_id FROM categories WHERE categories.category_slug = "'. $slug .'")'
        }

Basically, I just want to do something if the user supplied a $slug variable, otherwise skip it.

Thanks.

+2  A: 

You are missing a semicolon in the $wheresql = line, causing a parse error.

You need to turn on error reporting to see these errors: error_reporting(E_ALL); in the head of the script will do the trick.

Pekka
Wow that is freaking embarrassing. Thank you very much. I'm not familiar with error reporting... I just tried putting it at the top of the .php file in question, but that didn't seem to do anything. But I'm sure that's covered elsewhere... thanks for the response.
Ian Storm Taylor
@Ian: Then you should `ini_set('display_errors', true)`.
nikic
@nikic You are a life saver.
Ian Storm Taylor
+2  A: 

I suspect that what you're looking for is is_null()

 function get_entries($order = 'newest', $slug = null) {

        $wheresql = '';
        if (!is_null($slug)) {  
            $wheresql = 'WHERE entries.category_id = (SELECT categories.category_id FROM categories WHERE categories.category_slug = "'. $slug .'")';
        }
Jonathan Fingland
Be careful - you need !is_null() don't forget '!' ("not is null")
seriyPS
@seriyPS: thanks for bringing it to my attention. error corrected.
Jonathan Fingland
+1  A: 

Commonly !empty() is the idiom you should use rather than isset(). Because isset only rings true for NULL values, where you mostly also want to count FALSE and the empty string in.

mario
+2  A: 

try if(!is_null($slug)){...} (don't forget '!' sign before is_null(), because you need "not is null")

also, mysql query not allow to use doublequote as string quotes, so you must use

"WHERE entries.category_id = (SELECT categories.category_id FROM categories WHERE categories.category_slug = '". mysql_real_escape_string($slug) ."')"

as you see, i change quotes to doublequotes and vice versa, also don't forget about escaping $slug for prevent SQL injections!

seriyPS
Thanks for the warning about escaping. Good point.
Ian Storm Taylor
Interestingly, the double quotes aren't giving me any errors.
Ian Storm Taylor
@Ian: Normally `"` is okay. Only if MySQL is in `ANSI_QUOTES` mode `"` may not be used for normal strings. Still it is better to use `'`.
nikic
Ah OK thanks for the heads up.
Ian Storm Taylor