开发者

How to use isset and null variables in functions

开发者 https://www.devze.com 2023-01-23 05:25 出处:网络
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 ou开发者_运

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 ou开发者_运维技巧t 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.


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.


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!


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 .'")';
        }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消