0

我有一个注册页面,它将注册数据插入数据库。它遵循以下原则:

if ($_POST['password'] == $_POST['conf_pass']){
        $user = $_POST['username'];
        $pass = $_POST['password'];

        $hash = md5(rand(0,1000));

        $accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)");
        $account_id = mysqli_insert_id($accres);
        $peopleres = mysqli_query($connection, "INSERT INTO people (lastname, firstname, accounts_id, birthdate, phonenumber, username, password, email, hash) VALUES($lastname, $firstname, $account_id, $birthdate, $phonenumber, $username, $password, $email, $hash)");

        $peoplerows=mysqli_fetch_assoc($peopleres);
        $person_id=$peoplerows[0];

        mysqli_query("INSERT INTO PeopleToRole (role_id) VALUES(1)");
        $email = $_SESSION['email'];
        $p->addContent("User Registered");
}

我最初使用 postgres 对所有这些进行了编程(同时在 apache 服务器上本地托管),但不得不更改为 mysqli,因为主机网站已经在使用 mysqli。

因此,此代码返回页面上的用户注册,因此 if 语句有效。但由于某种原因,插入语句不会向数据库中插入任何内容。

我有某种格式错误吗?还是我错过的小东西?任何和所有的帮助将不胜感激。谢谢

4

2 回答 2

3

您忘记了查询中的引号,例如,您应该更改:

"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)"

至:

"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES('$address', '$suburb', '$city', '$postcode', '$username')"

也就是说,这样工作会使您的代码容易受到 sql 注入的影响(正如上面评论中提到的 cfreak )。

以下是手册中的一个小示例,展示了如何bind_param()使代码更安全:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();
于 2013-10-01T01:35:34.687 回答
1

一个常见问题:您不必费心检查查询是否有错误,因此当出现问题时您不知道发生了什么。

mysqli_query()检查for的返回值FALSE,如果找到,请检查mysqli_error($connection)错误消息。

例如:

$accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)");
if ($accres === false) {die(mysqli_error($connection));}

为您的其他查询做类似的事情。当您收到错误消息时,请修复它,或返回并再次询问。

于 2013-10-01T01:35:24.637 回答