0

I am trying to get MySQL decimal field types to work nice and I just can't figure it out. I send a $_POST['price'] field to a decimal field, for example 3.45, and it always stores it as 3.00.

What would I be doing wrong for it to not store the decimals?

Found the solution: PDO::PARAM for type decimal?

PDO has not decimal storing type, seems like something massive to miss out. Need to store it as a string not a numeric number.

Community
  • 1
  • 1
NaughtySquid
  • 1,947
  • 3
  • 29
  • 44
  • Could you add some code to the question, please? The PHP you're using to write to the database, at least, and the table definition would also be helpful. – andrewsi Jul 19 '13 at 19:03
  • 2
    change data type of the column to decimal (10,2) –  Jul 19 '13 at 19:03
  • What is the schema definition of that column? – tadman Jul 19 '13 at 19:08
  • updated it, found answer – NaughtySquid Jul 19 '13 at 19:13
  • You definitely have to escape it through `PDO::PARAM_STR`, then DB engine should make the conversion for you "pure insert"-speaking ... If you are doing some counting in your query, it should do that too. If for whatever reason your DB engine doesn't know instruction in a form of arithmetic operators (+, - , * , ...), you could `CAST()`/`CONVERT()` - but I do not recommed that... Anyway the 2nd main thing is to have the right data type for the column. – jave.web Aug 17 '16 at 16:27

1 Answers1

0

Use floatval() when converting the $_POST['price'] variable from a string to a floating point. This value is what should be stored in your database.

Be wary though! Floating point arithmetic is not so great when computing prices due to possible rounding errors. When dealing with price, I typically use integer arithmetic and then manually put in the decimal point.

So In your example I would store 345 to represent $3.45

Kirk Backus
  • 4,776
  • 4
  • 32
  • 52