在插入数据库之前键入转换?

时间:2013-08-27 02:03:18

标签: php mysql int typecasting-operator

请考虑以下代码段:

$day = '3'; // form input 

...

$stmt = $conn->stmt_init();
$q = 'INSERT INTO recording (release_day) VALUES(?)';
$stmt->prepare($q);
$stmt->bind_param('i', $day);
$stmt->execute();
...

变量 $ day 是表单输入中的字符串,但我将其绑定到整数。数据库列是smallint数据类型。

我假设数据库正在获取整数,对吧? 在绑定之前我是否需要进行某种类型的转换? 什么被认为是一种好的做法?

2 个答案:

答案 0 :(得分:1)

$i = 1; // PHP Casts to integer because the lack of quote marks for example.
$i = "1"; // PHP Casts to string because of the quote marks 
$i = 1.39; // PHP Casts to float because of the decimal place

当您创建变量时,这些是自动数据转换,因此不需要为您的变量进行二次转换,只需查看MySQL手册以查看smallint的限制/最大字节大小。确保您制定服务器条件,并且您不会遇到问题http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

答案 1 :(得分:1)

  

在绑定之前我是否需要进行某种类型的转换?

您已经在这里进行了类型转换:

$stmt->bind_param('i', $day);

这会将$day强制转换为整数,因为第一个参数值为'i',然后将该值传递给数据库。

例如,如果您的变量为'123hello',则只会传递123