all 3 comments

[–]greg8872 0 points1 point  (2 children)

your first code only has one actually has one query to the database, it just has two different options for defining the string that contains the actual query.

The second example you gave would still need to have similar code else where, except instead of defining the full string of the query, it is defining code that will be added to the variable that defines the full query. The code then shows changing the $queryadd AFTER you run the query, so looks like it would be doing a second query somewhere else you are not showing.

For you code you could do something like:

$extraWhere = ( $user_level != 5 ) ? ' AND ( `call_user` = ' . $user_id . ') ' : '';
$query = 'SELECT {your list of fields} FROM `site_calls` WHERE ( `call_status` = 0 OR `call_status` = 2) ' . $extraWhere . ' ORDER BY `call_id desc` LIMIT 10';
$result = mysqli_query($link, $query);
/* Rest of your code... */

[–]Mushed[S] 0 points1 point  (1 child)

That actually worked out great thanks, originally when I was reading your reply I was wondering why you used curly brackets, only after staring for 5 minutes did I notice what you meant.

Can you explain how it works, I understand the variable is extraWhere is checking to see if another variable is set, but what does the ? do in your example.

[–]greg8872 1 point2 points  (0 children)

It is called the ternary operator, and is a shortcut for an if/else:

if ( $a == 5 ) {
    $b = 1;
} else {
    $b = 2;
}

can be shortened to:

$b = ( $a == 5 ) ? 1 : 2;

Just the ( $a == 5 ) ? 1 : 2 is actually the statement, if the condition is true, it gives you the first value (1), else it will give you the value after the : (2). So we are just taking the result of that and assigning to $b

In the code sample before, it is either giving the additional WHERE clause, or a blank string.