PHP number_format and insert to DB

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
energylevel
Forum Newbie
Posts: 4
Joined: Mon Nov 08, 2004 5:11 am

PHP number_format and insert to DB

Post by energylevel »

I'm retrieving values from MySQL numeric field and want to format with a comma separator for 1000s like this: 21,000

This code below seems to work for display - how do I strip out the commas again before updating and inserting into MySQL DB?

<input type="text" name="Price id="Price value="<?php echo number_format($row_['Price'])); ?>" size="10" />
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP number_format and insert to DB

Post by McInfo »

Use str_replace() to replace the comma with an empty string. Or, better, use preg_replace() to strip out everything except digits and periods.

Code: Select all

str_replace(',', '', '5,432.10'); // Returns "5432.10"
str_replace(',', '', ' $5,432.10 '); // Returns " $5432.10 "
preg_replace('/[^\d.]+/', '', ' $5,432.10 '); // Returns "5432.10"
These could be transcription errors, but in the the HTML/PHP you posted, the name and id attributes of the input tag are missing closing quotes and there is an extra parenthesis after number_format().
Post Reply