最初发布的代码存在一些问题。首先,您最初确定的两个问题的原因是误用
mysqli::real_escape_string()
。它需要被调用
每个变量单独
其出现在代码中。因此,与其在整个语句中调用它,不如对多个变量多次调用它,例如:
$article = $connection->real_escape_string($connection);
由于引用错误导致查询失败(由于
real_escape_string()
)是错误消息调用的原因
close()
.
如评论中所确定的,您正在使用
num_rows + 1
以验证是否已根据先前返回的行数插入了一个新行。这是一个问题,原因有几个。主要是,它暴露了一种竞争条件,其中一行可以同时从两个会话中插入,其中一个或两个会话将失败,因为
$newrows
不匹配。真正地
BlogID
应该是
auto_increment
列。这消除了
任何
围绕它的逻辑。你甚至不需要在
INSERT
因为它将自动递增。
这也完全消除了第一个
SELECT
陈述
替换MySQL的本机
NOW()
函数,可以将语句简化为:
INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())
要测试插入的成功或失败,只需验证其变量是否
false
.
把这些放在一起,您的代码可以简化为:
if (!isset($_POST['article'])) {
// exit or handle an empty post somehow...
}
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
// Escape $article for later use
$article = $connection->real_escape_string($_SESSION["article"]);
// Only an INSERT is needed. $article is already escaped
$sql = "INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())";
// Run the query
$res = $connection->query($sql);
// Test for failure by checking for a false value
if ($res) {
// The connection & resource closure can be omitted
// PHP will handle that automatically and implicitly.
header( 'Location: adminpanel.php' );
// Explictly exit as good practice after redirection
exit();
}
else {
// The INSERT failed. Check the error message
echo $connection->error;
}
这将使您的当前代码进入工作状态。然而,由于您正在学习这一点,现在是开始学习使用准备好的语句的绝佳时机
prepare()/bind_param()/execute()
在MySQLi中。虽然使用了
real_escape_string()
只要你正确使用它并且永远不会忘记,它就可以工作。
看见
How can I prevent SQL injection in PHP
例如。
但它看起来像:
// connection already established, etc...
// Prepare the statement using a ? placeholder for article
$stmt = $connection->prepare("INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES (?, NOW())");
if ($stmt) {
// bind in the variable and execute
// Note that real_escape_string() is not needed when using
// the ? placeholder for article
$stmt->bind_param('s', $_SESSION['article']);
$stmt->execute();
// Redirect
header( 'Location: adminpanel.php' );
exit();
}
else {
echo $connection->error;
}