Reputation: 33
I am new to MySQL an PHP and not sure how to do this.
I am displaying:
<?php echo "$cash"; ?>
on my page. Which works just fine.
What I would like to do is, if it is a negative number I would like the number to be red if it is a positive number I would like the number to be green the font color that is.
Any help would be appreciated, thank you.
<?php $class = ($cash < 0) ? 'red' : 'green' ?>
<p class="<?php echo $class; ?>"> <?php echo $cash; ?> </p>
<style>
.red { color: red }
.green { color: green }
</style>
this works, but i would like the '$' to be included. Example:
-$100
$100
Upvotes: 0
Views: 3659
Reputation: 17034
Try this
<style>
.red { color: red }
.green { color: green }
</style>
<?php if ($cash < 0): ?>
<p class="red">- $ <?php echo ($cash * -1); ?></p>
<?php else: ?>
<p class="green">$ <?php echo $cash; ?></p>
<?php endif; ?>
If you have a UTF-8
document, you can write $
instead of $
Upvotes: 1
Reputation: 8855
In a cleaner way :
<?php $class = ($cash < 0) ? 'red' : 'green' ?>
<p class="<?php echo $class; ?>"> <?php echo $cash; ?> </p>
<style>
.red { color: red }
.green { color: green }
</style>
$cash
must be an integer for the condition to work properly. So in your MySQL you must only store in the cash column the actual value. A common practice is to store on another column the currency of the ammount you're storing. Or just hardcode it like :
<p class="<?php echo $class; ?>"> $<?php echo $cash; ?> </p>
Upvotes: 2
Reputation: 366
First of all, you can just do an
echo $cash
You don't need to put it in quotes.
For your question, you can do this without mySQL.
<?php
if($cash < 0) {
echo '<font color="red">' . $cash . '</font>';
} else {
echo '<font color="green">' . $cash . '</font>';
}
?>
One other way to do this without redundant font color tags is the following
<?php
if($cash < 0) {
$fontColor = 'red';
} else {
$fontColor = 'green';
}
echo '<font color="' . $fontColor . '">' . $cash . '</font>';
?>
If you want to be more up to date and avoid using the old school font tags, you can use css styles.
<?php
if($cash < 0) {
$fontColor = 'red';
} else {
$fontColor = 'green';
}
echo '<span style="color: ' . $fontColor . ';">' . $cash . '</span>';
?>
Edit: OR, you can do what sf_tristanb suggested. As you can see there are a lot of different ways you can do this. :)
Upvotes: 0