在数据库中插入之前进行类型转换


Type casting before inserting in database?

考虑以下代码片段:

$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数据类型。

我假设数据库是一个整数,对吧?在装订之前,我需要做一些类型转换吗?什么被认为是好的做法?

在装订之前,我需要做一些类型转换吗?

您已经在这里进行类型铸造:

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

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

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

$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