指定PHP sql查询的参数

时间:2011-11-16 21:13:06

标签: php mysql sql

我想使用PHP在SQL查询中指定原始用户名/密码:

function doRegister($username, $password) {
    $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die('error');
    $query = "SELECT username FROM users WHERE username = $username";
    $result = $db->query($query);
    if (mysqli_num_rows($result) == 1) {
        $msg = 'Username already taken';
    } else {
        $register = "INSERT INTO users(username, password)" .
                    "VALUES($username, SHA($password))";

        //error happens here
        $db->query($register) or die('error registering your account');


        $msg = "Register successful";
    }
    $db->close();
    echo $msg;
}

我在$db->query($register)收到错误消息。我做错了什么?

2 个答案:

答案 0 :(得分:6)

您没有用$username$password引号括起来,所以传递一个整数时它可以正常工作但不接受字符串:

$query = "SELECT username FROM users WHERE username = '$username'";
//----------------------------------------------------^^^^^^^^^^^^

$register = "INSERT INTO users(username, password)" .
                    "VALUES('$username', SHA('$password'))";
//-------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

请确保您已使用mysql_real_escape_string()正确转义了这些值。

这些列实际上不应该是TEXT类型。他们应该是VARCHAR()。也许您的VARCHAR()尝试失败了,因为您缺少长度参数,如VARCHAR(32)中最多32个字符。

答案 1 :(得分:1)

试试这个:

       function doRegister($username, $password) {
        $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die('error');
        $query = "SELECT username FROM users WHERE username = '$username'";
        $result = $db->query($query);
        if (mysqli_num_rows($result) == 1) {
            $msg = 'Username already taken';
        } else {
            $register = "INSERT INTO users(username, password)" .
                    "VALUES('$username', SHA('$password'))";
            $db->query($register) or die('error registering your account');
            $msg = "Register successful";
        }
        $db->close();
        echo $msg;
    }