我多年来一直在使用准备好的插入语句,并假设它正确地绑定(bind)了参数,否则会给出错误,但它似乎不像以下 php 绑定(bind)并插入一条记录而没有任何错误,但更改了一个应该是 int 的字符串到零。因此,它可能可以防止 SQL 注入(inject)攻击,但最终会在表中得到虚假记录。例如:
$q = "INSERT INTO `table` (id1, id2) VALUES (?, ?)";
$stmt = mysqli_stmt_init($dbc);
$stmt->prepare($q);
$id1 = 'aaaaaaa';
$id2= 'aaaaaaa';
$result = $stmt->bind_param('ii', $id1, $id2);
echo '<p>' . $result . '</p>'; // Trying to bind a string to an int returns true!
echo $dbc->error; // nothing
$stmt->execute(); // inserts record changing $id2 to zero but auto-increments primary key $id1
echo $dbc->error; // nothing
它在具有 Apache/2.2.14、PHP/5.3.1 和 MySQL 5.1.41 的 Xampp 环境中运行。谁能告诉我发生了什么事吗?
最佳答案
$stmt->bind_param() 不会检查给定变量的特定类型,它只会将它们转换为指定的类型。并且你的字符串 'aaaaaaa' 被转换为 int-value: 0。这就是 php 的做法。
如果变量包含有用/正确的值,则数据库插入语句是错误的检查位置。如果您的验证有效,请先执行此操作,然后仅尝试插入它们。
要对 int 进行验证,您可以使用 php 函数 is_numeric() 或 is_int()。
关于php - MYSQLI准备语句bind_param类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17548988/