php - 警告: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 行
我做错了什么?
解决方案
首先,不要责怪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);
}
推荐阅读
- excel - 如何获取地址单元格
- amazon-web-services - Websocket $connect 成功响应不会导致任何客户端/浏览器成功
- python - Apache Beam - Python:如何通过累积获得 PCollection 的前 10 个元素?
- amp-html - 从谷歌缓存提供服务时 AMP 页面显示无效
- android - 标记对拖动反应不灵敏
- javascript - Angular:想要在图表的条内显示名称
- sql-server - 如何在 SQL 中将逐行执行转换为基于 SET 的方法
- r - 如何将具有空格和 NA 的列变成一个因子?我们可以把字符变成数字吗?
- python - 在 Python 中复制 C 定点数学
- python - 试图理解为什么这段代码不返回相同的值