gpt4 book ai didi

php - mysqli (multi)_query - 如何在循环中执行和执行?

转载 作者:行者123 更新时间:2023-11-29 14:32:42 25 4
gpt4 key购买 nike

在为我的新网站创建了一些函数后,我很快意识到使用永久编程的所有包含文件都变得失控,因此我决定学习并将我当前编写的函数转换为 OOP 类并从 mysql 转换到 mysqli。到目前为止,过渡还不算太糟糕,但我已经达到了一个具有/需要多个查询的函数,其中一个是在更新之前检查数据的 SELECT 。到目前为止我所写的内容,使用准备好的语句,工作起来就像一个魅力,但它只执行 SELECT。我陷入困境的是更新数据库的时间。这是我到目前为止所拥有的:

public function ban() {
$connection = Database::getConnection();
$user_id = $_POST['user'];
$feedback = '';
$query = "SELECT banned, user_name
FROM users
WHERE user_id = ?";
$stmt = $connection -> prepare($query);

// Check for a multi-user selection on POST
if (count($user_id) > 1) {
foreach ($user_id as $value) {
$stmt -> bind_param('i', $value);
if (!$result = $stmt -> execute()) {
$feedback .= "Did not execute.";
} else {
$stmt -> bind_result($banned, $user);
$stmt -> fetch();
if ($banned == 1) {
$feedback .= $user . " is already banned.<br />";
} else {
// This is where I need the code to update the database
// with the users who aren't already banned.
}
}
}
$stmt -> close();
return $feedback;
} else {
// This is where the UPDATE will be for a single person ban
// if only one was selected on POST
}
}

我可以为更新注入(inject)创建/执行第二个准备好的语句,在我需要代码的部分中的另一个循环中运行该语句,还是最好避免这种情况,或者这是否有效?我确信 mysqli_multi_query 可能是最好的方法,必须再次重写该函数,因为我发现(在编写了这么多函数之后)您不能将准备好的语句与 multi_query 注入(inject)一起使用。重写并不是什么大问题,但使用 multi_query 的帮助却少之又少。 PHP 网站有很多文档,但说实话,它非常令人困惑。

UPDATE 查询看起来像这样:

$explain = mysql_real_escape_string($_POST['banExplain']);
UPDATE users
SET banned = '1', ban_reason = '$explain'
WHERE user_id = '$value'"

任何对此的帮助将不胜感激。希望我能很好地解释我需要做什么。如果没有,请告诉我。谢谢!

最佳答案

代码示例仍然非常程序化。

您应该有一个方法来检查用户是否被禁止,以及一个方法来禁止用户。

user_banned 方法应采用 user_id 并返回 bool 值。

ban_user 方法应该带有原因和 user_id。

应该有另一个函数或方法来执行循环。

将 user_id 转换为数组,您可以执行一个循环。

使用异常来处理错误。

<?php
//the model
...

public function update_users (array $user_ids)
{
$result = array();

foreach ($user_ids as $user_id) {
if (!$this->user_banned($user_id)) {
$this->ban_user($user_id, $reason);

} else {
$result[$user_id] = "already banned";
}

return $result;
}
...

//the controller

//prevent XSS, cast as integers or use filter_var or something
$user_ids = sanitize((array) $_POST['user']);
try {
$result = $obj->update_users($user_ids);
} catch (Exception $e) {
...

关于php - mysqli (multi)_query - 如何在循环中执行和执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com