0

i have the following MySQL-Query:

$sql = "SELECT `eid` FROM `"._ST_EVENT."` WHERE `tid` = ".$tid." AND DATE(`zeitpunkt`) >= CURDATE() ORDER BY `zeitpunkt` ASC;";

The variable $tid could be NULL, but should be interpreted as '0'. Is it possible to do this directly in the mysql-query or should i have a if-clause like this before executing the query?

if ($tid == NULL) {
    $tid = 0;
}

Thanks!

1
  • warning your code may be susceptible to sql injection attacks. Commented Jun 2, 2012 at 11:51

5 Answers 5

1

COALESCE(id, 0) in mysql is your friend :)

Read more here

Sign up to request clarification or add additional context in comments.

7 Comments

if id=null i think will return null not 0 as i have understand
from doc: Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
@khaled_webdev why dont you just try select COALESCE( null, 0 ), COALESCE( 'not null', 0 ); and check the results.
Well, programming is nice because there are many ways to solve the same problem. If it was Tar whose solution was fitting you the most, make sure you upvote it and mark as an answer :)
P.S. I was not really sure if I understood what you meant by COALESCE(selected_team, 0) being still NULL. It just is impossible :)
|
1

Use this condition:

"WHERE `tid` = ".($tid==null?0:$tid)."

1 Comment

i have write it in short time cause buzzy
0

Or:

$sql = "SELECT `eid` FROM `"._ST_EVENT."` WHERE `tid` = ".(!$tid ? 0 : $tid)." AND DATE(`zeitpunkt`) >= CURDATE() ORDER BY `zeitpunkt` ASC;";

Comments

0

Use ifnull in your query.

$sql = "SELECT `eid` FROM `"._ST_EVENT."` WHERE `tid` = ifnull(".$tid.",0) AND DATE(`zeitpunkt`) >= CURDATE() ORDER BY `zeitpunkt` ASC;";

1 Comment

@Torben I am not sure, why COALESCE is not working on your end. Alternatively you can try ifnull on the column value.
0

If you not prefer ANSI SQL you can use mysql IFNULL(id, 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.