January 26, 2011 in PHP & MySQL
I was recently faced with the situation of needing to enter a dollar amount from a <form> via PHP to a MySQL Database. This may sound like a simple feat, but it resulted in being completely the opposite. The reason being is that when data is “uploaded” into MySQL, it views a comma as being the end of a string. So, when the amoutn 75,000 is entered, the amount that MySQL actually “sees” is 75. To find the solution took me a bit longer than expected. And, as per usual, it ended up being something simple to correct.
To removed the “,” from the string:
|<?php $price = ereg_replace(“,”, “”, $_POST['nprice']); ?>|
Let’s break this down: ereg_replace function is to stating, locate the “,” in the $_POST['nprice'] string and replace it with “”, which is nothing. You can place anything inside the first “” of any symbol you would like removed. Now the data is clean and ready to be uploaded into MySQL accurately. The next solution to find, is how do we show the number (example: 75000) as a currency? That proved to be much simpler.
|<?php echo number_format($price); ?>|
This indicates that the value stored in $price should be shown in a number format (example: 75,000).
To learn more about the function ereg_replace: http://php.net/manual/en/function.ereg-replace.php
To learn more about the function number_format: http://php.net/manual/en/function.number-format.php