Robert E Lynds-Marler
Robert E Lynds-Marler

Reputation: 33

changing font color of data from database using php

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

Answers (3)

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

Try this

<style>
    .red { color: red }
    .green { color: green }
</style>

<?php if ($cash < 0): ?>   
    <p class="red">- &#36; <?php echo ($cash * -1); ?></p>
<?php else: ?>    
    <p class="green">&#36; <?php echo $cash; ?></p>
<?php endif; ?>

If you have a UTF-8 document, you can write $ instead of &#36;

Upvotes: 1

sf_tristanb
sf_tristanb

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

user3842536
user3842536

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

Related Questions