将字符串转换为mySql DECIMAL类型

将字符串转换为mySql DECIMAL类型

问题描述:

我正在尝试将有关商品价格的数据从HTML表单插入MySQL数据库。输入字段定义如下:

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"/>

将表单过帐到处理数据库内容的下一页。目前,我只是将$ _POST ['price']的确切内容输入到数据库字段中,该字段的类型为DECIMAL(4,2)。我听说这存储为字符串,但是每当我尝试执行此操作时,数据库都会引发错误。是否有PHP函数可以在字符串和MySQL DECIMAL类型之间进行转换?还是我必须对自己进行格式化?

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?

您永远不应该只是 输入 $ _ POST ['...'] 插入任何数据库字段:这是SQL注入的大门。

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

相反,必须根据预期的数据库数据类型,确保注入到SQL查询中的数据实际上是有效的。

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



对于小数,在PHP方面,一种解决方案是使用 floatval 函数:

$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 ;-)