警告:mysqli_stmt_init() 期望参数 1 为 mysqli,给定为空

Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given

我正在为网站制作聊天功能,但我不擅长 PHP:

<?php

if (isset($_POST['send'])) {
    require 'database.php';

    $input = $_POST['input'];
} else {
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    } else {
        mysqli_stmt_bind_param($stmt, "sss", $input);
        mysqli_stmt_execute($stmt);
        header("index.html?request=success");
        exit();
    }
}
{
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}

和数据库代码:

<?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

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

这导致:

Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11
Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11
Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12

我做错了什么?

首先,不要责怪PHP,因为它是一种功能强大且易于使用的服务器端语言,尝试靠近你会爱上它。

其次你有不必要的if else,还传递了额外的参数给bind param,而你只有一个要传递。

<?php

if (isset($_POST['send'])) {
    require 'database.php';
    $input = $_POST['input'];
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);

    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    }
    //No need to else here because if error happens you get back and exit.
    mysqli_stmt_bind_param($stmt, "s", $input);
    mysqli_stmt_execute($stmt);
    header("index.html?request=success");

    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}

您的代码过于复杂了。您不需要所有这些大括号或 if 语句。如果启用错误报告,则不需要检查 mysqli 调用的 return 值。

<?php

// If value was posted to the server
if (isset($_POST['send'])) {
    // include mysqli connection
    require 'database.php';

    // perform prepared statement. (prepare/bind/execute)
    $stmt = $conn->prepare("INSERT INTO chatsys (chat) VALUES (?)");
    $stmt->bind_param("sss", $_POST['input']);
    $stmt->execute();
    // redirect on success
    header("index.html?request=success");
    exit();
}

和您的连接文件:

<?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
$conn->set_charset('utf8mb4'); // always set the charset