homepage Welcome to WebmasterWorld Guest from 174.129.130.202
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Adding Dollar signs to numeric values
lndlyb4




msg:3985641
 6:28 pm on Sep 7, 2009 (gmt 0)

Hi,

I have a page that displays the prices for different products. Some of the products are not available in all sizes, so a "n/a" (not available) is displayed. I would like to add code to insert a $(dollar sign) to the front of all prices, but to leave it off if the value displayed is "n/a" or some kind of text.

Below is the code for the display page.

Thanks in advance for any help.

<?php

//Attempt to connect to MySQL and print out messages.

if($dbc = @mysql_connect ('localhost','---','----')) {

//print '<p>Successfully connected to MySQL.</p>';

} else {

print '<p>Could not connect to MySQL.</p>';

}

if (@mysql_select_db ('---')) {

//print '<p>You successfully selected the Contact Manager Database.</p>';

} else {

die ('<p>Could not select the database because: <b>'
. mysql_error() . '</b></p>');

}

$products_id = addslashes($_POST['products_id']);
$products_name = addslashes($_POST['products_name']);
$products_common_name = addslashes($_POST['products_common_name']);
$container_4_inch = addslashes($_POST['container_4_inch']);
$container_4_5_inch = addslashes($_POST['container_4_5_inch']);
$container_1_gal = addslashes($_POST['container_1_gal']);
$container_3_gal = addslashes($_POST['container_3_gal']);
$container_5_gal = addslashes($_POST['container_5_gal']);
$container_7_gal = addslashes($_POST['container_7_gal']);
$container_10_gal = addslashes($_POST['container_10_gal']);
$container_15_gal = addslashes($_POST['container_15_gal']);
$container_20_gal = addslashes($_POST['container_20_gal']);
$container_25_gal = addslashes($_POST['container_25_gal']);
$container_45_gal = addslashes($_POST['container_45_gal']);
$container_65_gal = addslashes($_POST['container_65_gal']);
$container_hb_8 = addslashes($_POST['container_hb_8']);
$container_hb_10 = addslashes($_POST['container_hb_10']);
$container_hb_12 = addslashes($_POST['container_hb_12']);



$query = "SELECT
p.products_id,
d.products_name,
p.products_common_name,
p.container_4_inch,
p.container_4_5_inch,
p.container_1_gal,
p.container_3_gal,
p.container_5_gal,
p.container_7_gal,
p.container_10_gal,
p.container_15_gal,
p.container_20_gal,
p.container_25_gal,
p.container_45_gal,
p.container_65_gal,
p.container_hb_8,
p.container_hb_10,
p.container_hb_12

FROM zen_products p, zen_products_description d WHERE p.products_id = d.products_id AND p.products_status = 1";

$result = mysql_query($query)
or die ("Couldn't execute query.");

//Display results in a table.

?>

<div id="count">

<?php
$query = mysql_query("SELECT
p.products_id,
d.products_name,
p.products_common_name,
p.container_4_inch,
p.container_4_5_inch,
p.container_1_gal,
p.container_3_gal,
p.container_5_gal,
p.container_7_gal,
p.container_10_gal,
p.container_15_gal,
p.container_20_gal,
p.container_25_gal,
p.container_45_gal,
p.container_65_gal,
p.container_hb_8,
p.container_hb_10,
p.container_hb_12

FROM zen_products p, zen_products_description d WHERE p.products_id = d.products_id AND p.products_status = 1");

$num_rows = mysql_num_rows($query);

echo "A total of" . " " . "<span>" . $num_rows . "</span> " . "plants are active.<br /><br />";

?>
</div><!--end of count div-->

<table id="contactDisplayList">

<tr>
<th id="products_name" class="tableHeader">Plant Name</th>
<th id="products_common_name" class="tableHeader">Common Name</th>
<th id="4_inch" class="tableHeader_cont">4 Inch</th>
<th id="4.5_inch" class="tableHeader_cont">4.5 Inch</th>
<th id="1_gal" class="tableHeader_cont">1 gal</th>
<th id="3_gal" class="tableHeader_cont">3 gal</th>
<th id="5_gal" class="tableHeader_cont">5 gal</th>
<th id="7_gal" class="tableHeader_cont">7 gal</th>
<th id="10_gal" class="tableHeader_cont">10 gal</th>
<th id="15_gal" class="tableHeader_cont">15 gal</th>
<th id="20_gal" class="tableHeader_cont">20 gal</th>
<th id="25_gal" class="tableHeader_cont">25 gal</th>
<th id="45_gal" class="tableHeader_cont">45 gal</th>
<th id="65_gal" class="tableHeader_cont">65 gal</th>
<th id="hb_8" class="tableHeader_cont">Hanging Basket, <br />8 inch</th>
<th id="hb_10" class="tableHeader_cont">Hanging Basket, <br />10 inch</th>
<th id="hb_12" class="tableHeader_cont">Hanging Basket, <br />12 inch</th>
</tr>

<!--<td><a href="http://www.example.com/zenCart_boe/priceManager/test.php?products_id={$products_id}">Edit</a></td>-->
<?php

while ($row = mysql_fetch_array($result))
{
extract($row);

print
'<tr class="rowHeight">

<td class ="leftAlign">'. $row['products_name'] . '</td>
<td class ="leftAlign">' . $row['products_common_name'] . '</td>
<td class ="centerAlign">'. $row['container_4_inch'] . '</td>
<td class ="centerAlign">' . $row['container_4_5_inch'] . '</td>
<td class ="centerAlign">' . $row['container_1_gal'] . '</td>
<td class ="centerAlign">' . $row['container_3_gal'] . '</td>
<td class ="centerAlign">' . $row['container_5_gal'] . '</td>
<td class ="centerAlign">' . $row['container_7_gal'] . '</td>
<td class ="centerAlign">' . $row['container_10_gal'] . '</td>
<td class ="centerAlign">' . $row['container_15_gal'] . '</td>
<td class ="centerAlign">' . $row['container_20_gal'] . '</td>
<td class ="centerAlign">' . $row['container_25_gal'] . '</td>
<td class ="centerAlign">' . $row['container_45_gal'] . '</td>
<td class ="centerAlign">' . $row['container_65_gal'] . '</td>
<td class ="centerAlign">' . $row['container_hb_8'] . '</td>
<td class ="centerAlign">' . $row['container_hb_10'] . '</td>
<td class ="centerAlign">' . $row['container_hb_12'] . '</td>

<td><a href="http://www.example.com/zenCart_boe/priceManager/test_6.php?products_id=' . $row['products_id'] . '">Edit</a></td>

</tr>';
}

?>

[edited by: eelixduppy at 6:32 pm (utc) on Sep. 7, 2009]
[edit reason] switched to example.com [/edit]

 

jman11




msg:3985647
 6:44 pm on Sep 7, 2009 (gmt 0)

i dont see where your prices are echoed but just do it like this:


echo '$'.$row['price'];

add <td> or whatever you want in front of the $ to add a table column or whatever you want

idfer




msg:3985667
 7:04 pm on Sep 7, 2009 (gmt 0)

Heh yes, not quite sure which values are the prices, i'm guessing $row['container_4_inch'] etc?

For this, functions are your best friends. Write a function like:

[pre]function formatPrice($price) {
if(!isset($price) $price === '')
return 'n/a';
else
return '$'.$price;
}[/pre]

Stick that at the bottom of your script, and change your print statement to:

[pre]print '<tr class="rowHeight">
<td class ="leftAlign">'. $row['products_name'] . '</td>
<td class ="leftAlign">' . $row['products_common_name'] . '</td>
<td class ="centerAlign">'. $row['container_4_inch'] . '</td>
<td class ="centerAlign">' . [b]formatPrice([/b]$row['container_4_5_inch'][b])[/b] . '</td>
<td class ="centerAlign">' . [b]formatPrice([/b]$row['container_1_gal'][b])[/b] . '</td>
...[/pre]

You can also look into the PHP function number_format() to format your price nicely with commas and the right number of decimal places.

Hope this helps.

rocknbil




msg:3985729
 9:09 pm on Sep 7, 2009 (gmt 0)

Welcome aboard lndlyb4!

TMTOWTDI even in PHP. :-)


function formatPrice($price) {
var $fnl = ($price>0)?'$'.$price:'n/a';
return $fnl;
}

This may work better because if your price is in decimal format, isset() will give you $0.00.

which values are the prices

Not always necessary . . . The way I handle these is to loop through the list of selected fields. By using appropriate price column definitions with a default value (e.g., decimal(12,2) default '0.00') you can do this.

var $example = Array('id','title','price','description');


foreach ($example as $field) {
$out .= '<td style="some-style">';
$out .= (preg_match('/^\d+\.\d+$/',$row[$field]))?formatPrice($row[$field]):$row[$field];
$out .= '</td>';
}

You can add other conditionals in your loop for alternating style rows, left/right align, truncating extended descriptions, etc.

lndlyb4




msg:3986623
 1:53 pm on Sep 9, 2009 (gmt 0)

jman11, idfer, rocknbil

Thank you so much for responding. I am new at php, so I really appreciate it.
I will try out your suggestions and let you know the results.

lndlyb4




msg:3987293
 1:15 pm on Sep 10, 2009 (gmt 0)

rocknbil,

I'm pretty new to php/mysql. Just a couple of questions on how to implement your code.

1. In the function, do I replace the "$price" variable with the price I want to go in the cell? Like this?

function formatPrice($container_4_inch) {
var $fnl = ($container_4_inch>0)?'$'.$container_4_inch:'n/a';
return $fnl;
}

2. Do I add the function name to the cell like this?

<td>' . formatPrice($fnl) . '</td>

I get this message: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/lndlyb4/public_html/blackoliveeast/zenCart_boe/priceManager/display_prices_6.php on line 200

If you have time for any further guidance, I would be grateful.

Bill

lndlyb4




msg:3987303
 1:22 pm on Sep 10, 2009 (gmt 0)

By the way, line "200" is where the <td>' . formatPrice($fnl) . '</td> is.

rocknbil




msg:3987462
 5:30 pm on Sep 10, 2009 (gmt 0)

1 and 2 - no, and no. I did have an error, sorry, the var keyword is not needed.

You give your kid a written message, tell them to take it to your friend, have them write a response to your message based on some agreed rules. You don't know what type of pencil or pen they wrote it with (the local value $fnl), all you know is the returned value written on the note (the new value of $row['container_4_inch'].)

This is the purpose of a function - send it a value and get a response. Your errors are most likely unrelated and due to a missing quote for string values or an error in the $row....value:

$me = 'Bill . $some_var . ' is here';
// error in the string, note missing '
$me = 'Bill ' . $some_var . ' is here';
// correct.

$me = $row['some-field];
// error
$me = $row['some-field'];
// correct.

Or a combination - error in the string literal, and PHP is encountering the error on the next array output, giving the encapsed error.

Put the below in a test file. You will get how it works. Tested code.


<?php
// Do not leave these two lines in any live application!
error_reporting(E_ALL);
ini_set("display_errors", 1);


// Some variables for the demonstration.
// Although I am storing them in NEW variables
// to demonstrate, you can store them in the same variables
// and overwrite the original, e.g.:
// $myprice = formatPrice($myprice);
$myprice = '22';
$badprice = 'I am not a number';
$my_new_price = formatPrice($myprice);
$my_new_bad_price = formatPrice($badprice);


// Now let's build an output string.
// A clarification on all the dots and 's.
// When you concatenate with ., you add string literals
// together with variables and can build a string multi-line.
// But to create an actual period, it must be within the quotes.
// Alteratively, you can use double quotes which will
// interpolate $variables, and you don't need to concatenate,
// But this means you have to escape all double quotes
// in the strings, which is a real pain for HTML attributes.
// PHP really needs an equivalent of perl's qq (O.T., sorry)
$out = '
<p>The original price is &quot;' . $myprice . '&quot; and is now &quot;' .
$my_new_price . '.&quot; The original bad price is &quot;' .
$badprice . '&quot; and is now &quot;' . $my_new_bad_price . '.&quot;</p>';


// Print it out.
header("Content-type:text/html");
print $out;
// or echo $out;


// Here is the function that converts the string.
// $price and $fnl are variables only available
// to this function. Note that I'm using it twice,
// it can be called any number of times. This is the
// purpose of functions and classes, re-usable code.
function formatPrice($price) {
// Note the addition of the sprintf function.
// This converts "22" into "22.00". Review the
// documentation for sprintf, it's extremely handy.
$fnl = ($price>0)?'$' . sprintf("%.2f",$price):'n/a';
return $fnl;
}
?>

lndlyb4




msg:3988910
 11:48 pm on Sep 13, 2009 (gmt 0)

rocknbil,

I am so grateful that you took the time to help me with this issue. I worked through your little tutorial and, as you suggested, it helped me to understand how the function works. I added it to my code and it works perfectly.

As I'm sure you know, learning to write a new code can be very confusing and frustrating, but it is a thing of beauty when it actually works - and a great sense of accomplishment.

Thank you for helping me.

Bill

bedlam




msg:3989380
 8:50 pm on Sep 14, 2009 (gmt 0)

I've used number_format [php.net] (as suggested by idfer) and sprintf [php.net] (as suggested in detail by rocknbil) for formatting currency amounts in the past, but IMO the best tool for this job is money_format [php.net].

-- b

lndlyb4




msg:3989960
 11:13 pm on Sep 15, 2009 (gmt 0)

bedlam,

Thanks for the input. I'm going to test your suggestion out when I get a minute.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved