0

I am retrieving a field from a database on a coupon site I am helping to develop. One of the fields has the promo info, for example, "Buy this product for only $10.99". When I retrieve the field and echo it, it parses the price as a variable, and I end up with "Buy this product for only .99"

How can I avoid this?

My code looks as follows:

$resultTitle = mysql_query("SELECT post_title FROM wp_posts WHERE ID = " . $f_couponId . " LIMIT 1") or die(mysql_error());
$valueTitle = mysql_result($resultTitle,0);
$echo("$valueTitle");

Thx!

Marc B
  • 356,200
  • 43
  • 426
  • 500
caBazan
  • 11
  • 4
    `$echo(...)` is totally invalid. echo is a language construct, not a variable. And there is NO need for `"$valueTitle"` a simple `echo $valueTitle` is all you need. – Marc B Oct 07 '14 at 21:42

4 Answers4

1
  1. You can escape $ by using a escape character like \ Use \$10.99.
  2. Also, dont use $echo, it is not a function.
  3. Dont use mysql now, it is depreciated, use mysqli instead.
Yash Sodha
  • 713
  • 3
  • 13
1

There is no way that echoing out a string which contains a $ would ever treat that $ as a variable.

e.g.

php > $foo = 'This string has a $ sign in it, and another $fake one as well';
php > echo "$foo";
This string has a $ sign in it, and another $fake one as well
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

http://php.net/manual/en/function.money-format.php

I've used that for inventory and small accounting systems. Hopefully it helps.

Andres P
  • 65
  • 2
  • 8
0

Two things you should do here;

  • Save the price in the database without the currency symbol

It's not required and can confuse both the database and you. Instead use it when echoing the price to the webpage. However ...

  • Don't use the $ symbol.

You don't need to as there is a HTML code that will display it for you ($). That way it will be standards compliant too. You should number format your variable before echoing the price too;

$price = number_format($valueTitle,2);
echo "$$price";

Also note you should use echo not $echo.

Additionally, your database is wide open to SQL injection. Please read How can I prevent SQL injection in PHP.

Hope this helps.

Community
  • 1
  • 1
worldofjr
  • 3,868
  • 8
  • 37
  • 49