将字符串转换为mySql DECIMAL类型 [英] Converting a string to a mySql DECIMAL type

查看:1341
本文介绍了将字符串转换为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?

推荐答案

您永远不应该只是 输入<$的确切内容 c $ c> $ _ 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 ;-)

这篇关于将字符串转换为mySql DECIMAL类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆