I am fetching an integer value from my database which might be positive, negative, or zero.
I want to show an icon depending on the values relation to zero using FontAwesome's font icons.
> 0
, I want to show the result with icon-caret-up
.= 0
, I want to show the result with icon-caret-right
.< 0
, I want to show the result with icon-caret-down
.So I added the following php code :
$reponse=mysql_query("My SQL Query");
if ($reponse > 0) {
echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">".(mysql_result($reponse, 0))."<i class=\"uk-icon-caret-up\"></i></h1>";
}
elseif ($reponse == 0) {
echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">".(mysql_result($reponse, 0))."<i class=\"uk-icon-caret-up\"></i></h1>";
}
else {
echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">".(mysql_result($reponse, 0))."<i class=\"uk-icon-caret-down\"></i></h1>";
}
Whatever the result, even when it's a negative figure or equal to zero, I got only the first choice displaying the icon-caret-up
.
First of all, the mysql_* functions are deprecated, you need to use PDO or MySQLi for new development.
Secondly, as the documentation says, mysql_query
returns a resource. http://php.net/mysql_query There are lots of examples on that page of how to use it.
You must fetch a row once you have executed the query. (Edit: I see you already know this because you're doing it in the next line, with mysql_result
- you just need to use it before trying to do your comparison.)
$row = mysql_fetch_assoc($reponse)
and then $row
will be an array of values. Since you haven't shown the actual field names you're selecing I can't tell you what to do next, but read the docs.
Now, once you get that code set, you can simplify your printing of the HTML a lot.
$amount = mysql_result($reponse, 0);
if($amount > 0){
$caret = 'up';
}else if($amount == 0){
$caret = 'right';
}else{
$caret = 'down';
}
echo '<h1 class="uk-text-center uk-margin-bottom-remove">'.$amount.'<i class="uk-icon-caret-'.$caret.'"></i></h1>';
Last line can also be echo "<h1 class=\"uk-text-center uk-margin-bottom-remove\">{$amount}<i class=\"uk-icon-caret-{$caret}\"></i></h1>";
But I personally find escaping quotes annoying. So I switched it.