dourao1896
2010-03-12 17:00
浏览 303
已采纳

将字符串转换为mySql DECIMAL类型

I am trying to insert data about an item's price from an HTML form into a mySQL database. The input field is defined as follows:

<input type="text" name="price" value="0.00"/>

The form is POSTed to the next page in which the database stuff is taken care of. Currently I just enter the exact contents of $_POST['price'] into the database field, which has type DECIMAL(4,2). I heard that this was stored as a string but the database throws an error whenever I try and do this. Is there a PHP function for converting between strings and the MySQL DECIMAL type? Or will I have to do some formatting myself?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试将有关项目价格的数据从HTML表单插入到mySQL数据库中。 输入字段定义如下:

 &lt; input type =“text”name =“price”value =“0.00”/&gt; 
  <  / pre> 
 
 

将表单发布到下一页,其中包含数据库内容。 目前我只需将$ _POST ['price']的确切内容输入数据库字段,该字段的类型为DECIMAL(4,2)。 我听说这是作为字符串存储的,但每当我尝试这样做时,数据库都会抛出错误。 是否有用于在字符串和MySQL DECIMAL类型之间进行转换的PHP函数? 或者我必须自己做一些格式化吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjiao5261 2010-03-12 17:07
    已采纳

    You should never just "enter the exact contents of $_POST['...']" into any database field : it's a door opened to SQL Injections.

    Instead, you must make sure the data you are injection into your SQL queries are actually valid, according to the expected DB datatypes.


    For decimals, a solution, on the PHP side, would be to use the floatval function :

    $clean_price = floatval($_POST['price']);
    $query = "insert into your_table (price, ...) values ($clean_price, ...)"
    if (mysql_query($query)) {
        // success
    } else {
        echo mysql_error();   // To help, while testing
    }
    

    Note that I didn't put any quote arround the value ;-)

    点赞 评论

相关推荐 更多相似问题