致命错误:未捕获错误:在 X 中的 int 上调用成员函数 stmt_init() 堆栈跟踪:#0 {main} 在 X 中抛出

问题描述 投票:0回答:1

我在尝试运行 /process-signup.php 后收到此错误,我正在尝试编写注册登录系统,但我被阻止在这里。

“process-signup.php”的代码;

<?php

if (empty($_POST["username"])) {
    die("Username is required");
}

if (strlen($_POST["password"]) < 8) {
    die("Password must be at least 8 characters");
}

if ( ! preg_match("/[a-z]/i", $_POST["password"])) {
    die("Password must contain at least one letter");
}

if ( ! preg_match("/[0-9]/", $_POST["password"])) {
    die("Password must contain at least one number");
}

if ($_POST["password"] !== $_POST["repassword"]) {
    die("Passwords must match");
}

$password_hash = password_hash($_POST["password"], PASSWORD_DEFAULT);

$mysqli = require __DIR__ . "/config.php";

$sql = "INSERT INTO user (username, password)
        VALUES (?, ?)";

$stmt = $mysqli->stmt_init();

if ( ! $stmt->prepare($sql)) {
    die("SQL error: " . $mysqli->error);
}

$stmt->bind_param("sss",
                $_POST["username"],
                $password_hash);

$stmt->execute();


echo "Signup successfull";
?>

“config.php”代码;

<?php

$conn = new mysqli('localhost','root', '', 'login_db','3306');

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

我真的不知道问题出在哪里,我期望“注册成功”

php mysql phpmyadmin
1个回答
0
投票

您将

require
的返回值分配给
$mysqli
。默认情况下,成功时会返回
1
,因此您将
$mysqli
设置为
1
,而不是数据库连接对象。

您有两个选择:

  1. 在主脚本中使用
    $conn
    而不是
    $mysqli
  2. 更改
    config.php
    以返回连接。
<?php

$conn = new mysqli('localhost','root', '', 'login_db','3306');

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
return $conn;
?>

当包含文件执行

return
时,该值将成为
include
require
调用的值。

© www.soinside.com 2019 - 2024. All rights reserved.