bind_param新手,这段代码出了什么问题?

时间:2015-02-26 00:29:30

标签: php mysql mysqli

        // Insert the new user into the database
        // This WORKS, and was copied from an example
        if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
            $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
            // Execute the prepared query.
            if (! $insert_stmt->execute()) {
                header('Location: ../error.php?err=Registration failure: MEMBER. Please contact the developer.');
            }
            $insert_stmt->close();



            // If user inserted, add place with user as owner
            // This DOESN'T work, and was added by me
            //$ownerid = $mysqli->lastInsertId();
            $placename = $_POST['placename'];
            $placename = mysqli_real_escape_string($mysqli, $placename);
            $location = $_POST['autocomplete'];
            $location = mysqli_real_escape_string($mysqli, $location);
            if ($place_stmt = $mysqli->prepare("INSERT INTO places (member_owner, location, name) VALUES (?, ?, ?)")) {
                $place_stmt->bind_param('iss', 1, $location, $placename);
                if (! $place_stmt->execute()) {
                    header('Location: ../error.php?err=Registration failure: PLACE. Please contact the developer.');
                }
            }
            $place_stmt->close();
        }

        header('Location: ./register_success.php');

我可以确认已成功检索到2个变量$location$placename。运行此代码得到的结果是members表已成功更新,但places表未成功更新,脚本将我转储为空白HTML。

1 个答案:

答案 0 :(得分:0)

我发现bind_param不喜欢接受硬编码值。我试图通过在我试图获取最后插入的ID之前将一个值1插入一列来“测试”我的代码。弗雷德建议的错误报告确实有帮助(正如其他建议一样,你可以看到我已经实施了)。

修改后的代码:

    // Insert the new user into the database 
    if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
        $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
        // Execute the prepared query.
        if (! $insert_stmt->execute()) {
            header('Location: ./error.php?err=Registration failure: MEMBER. Please contact the developer.');
            exit;
        }
        $insert_stmt->close();

        // If user inserted, add place with user as owner
        $ownerid = $mysqli->insert_id;
        if ($place_stmt = $mysqli->prepare("INSERT INTO places (member_owner, location, name) VALUES (?, ?, ?)")) {
            $place_stmt->bind_param('iss', $ownerid, $location, $placename);
            if (! $place_stmt->execute()) {
                header('Location: ./error.php?err=Registration failure: PLACE. Please contact the developer.');
                exit;
            }
        }
        $place_stmt->close();
        header('Location: ./register_success.php');
    }

感谢您的帮助!