首页 > 解决方案 > 警告:mysqli_stmt_init() 期望参数 1 为 mysqli,给定 null

问题描述

我正在为网站制作聊天功能,但不擅长使用 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());
}
?>

这导致:

注意:未定义的变量:第 11 行 C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php 中的 conn
警告:mysqli_stmt_init() 期望参数 1 为 mysqli,在 C:\Users 中给出 null \John Doe\Desktop\server\htdocs\php\message\chat.php 第 11 行
警告:mysqli_stmt_prepare() 期望参数 1 为 mysqli_stmt,在 C:\Users\john doe\Desktop\server\htdocs\php 中给出 null \message\chat.php 第 12 行

我做错了什么?

标签: phpmysqli

解决方案


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

其次,您有不必要的 if else,并且还传递了额外的参数来绑定参数,而您只有一个要传递。

<?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);
}

推荐阅读