-1

因此,经过数小时的调试,我找不到让我的代码正常工作的方法。如果有人可以帮助我或指出我正确的方向,那将不胜感激。另外,我该如何保证这部分代码的安全?

if (empty($_POST) === false && empty($errors) === true) {
                $register_data = array(
                    'username' => $_POST['username'],
                    'password' => $_POST['password'],
                    'email' => $_POST['email'],
                    'email_code' => md5($_POST['username'] + microtime())
                );
                register_user($db, $register_data);
                header('location: register.php?success');
                exit();
            }

然后是register_user函数

function register_user(PDO $db, $register_data) {
    array_walk($register_data, 'array_sanitize');
    $register_datapw = $register_data['password'];
    require ('blowfish.class.php');
    $bcrypt = new Bcrypt(4);
    $register_datapw = $bcrypt->hash($register_datapw);

    $fields = '`' . implode('`, `', array_keys($register_data)) . '`';
    $data = '\'' . implode('\', \'', $register_data) . '\'';

    $query = "INSERT INTO `users` ($fields) VALUES ($data)";
    $stmt = $db->prepare($query);
    $stmt->execute();   
}

错误~ Argument 1 passed to register_user() must be an instance of PDO, array given, called in...

我觉得我已经把自己挖进了一个我找不到出路的洞,实际上我的大脑被炸了,但我已经设法完成了我的错误报告和调试,直到我终于到达顶峰,我难住了!

编辑:

我已经按照你说的做了,我相信它有效,但现在我面临这个问题。 mysql_real_escape_string(): A link to the server could not be established

function array_sanitize(&$item){
$item = htmlentities(strip_tags(mysql_real_escape_string($item)));
}
4

1 回答 1

0

当您使用 PDO 准备方法时;尽量不要将您的值作为字符串传递给查询,而是绑定它们或在运行时提供它们:

$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = ':' . implode(', :', array_keys($register_data)) . '';

$query = "INSERT INTO `users` ($fields) VALUES ($data)";
stmt = $db->prepare( $query );
$stmt->execute( $register_data );
于 2013-05-09T01:05:04.433 回答