0

I have the following table

CREATE TABLE IF NOT EXISTS `payment_data` (
  `orderid` int(11) NOT NULL,
  `orderDesc` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `orderAmount` float NOT NULL,
  UNIQUE KEY `orderid` (`orderid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

and I'm trying to insert a line in it using PHP.

$sql = 'INSERT INTO payment_data '.
           '(orderid, orderDesc, name, email, orderAmount) '.
           'VALUES ( '.$form_order_id.', "'.$form_order_desc.'", "'.$form_name.'", "'.$form_email.'", '.number_format($form_order_amount, 2, '.', ',').' )';

The problem is that "orderAmount" is inserted without the decimal part. For example if $form_order_amount=30,45 then 30 is what's inserted in database.

I used number_format() because it's supposed to convert "30,45" to "30.45".

4
  • You need the decimal precision for float orderAmount float(7,2)` or something desireable Commented Oct 1, 2014 at 8:41
  • 30,45 with a , decimal is not a valid number to a computer; you need a decimal point (.) when inserting to MySQL Commented Oct 1, 2014 at 8:42
  • 2
    That said, don't use float for database money, use decimal.... or even better, adjust the value to cents so you're working with integers if you ever need to do adjustments for tax calculations, etc where floating point precision may cause issues Commented Oct 1, 2014 at 8:43
  • 1
    number_format() should be used when displaying a float value, not internally when storing it, and it won't convert 30,45 to 30.45, but will do the reverse Commented Oct 1, 2014 at 8:45

2 Answers 2

3

Convert form_order_amount to float first, using this:

$form_order_amount = floatval(str_replace(',', '.', $form_order_amount));
Sign up to request clarification or add additional context in comments.

Comments

0

I had a similar problem. This is how I did it. Source php manuals

public static function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
            ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
        preg_replace("/[^0-9]/", "", substr($num, $sep + 1, 
        strlen($num)))
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.