我试图从数据库表中删除一行,并且我的msqli准备语句返回false。我已经错误地检查了$ commentId并正确地传递了它。但是我找不到它不起作用的原因。

请帮忙!

<?php
session_start();

include('connect.php');

if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == true && $_SESSION['id'] == 43) {
    DeleteRowFunction($_POST['commentId']);
} else {
    echo "You are not authorized to delete comments";
}

function DeleteRowFunction($commentId) {
    //$deleteComment = "DELETE FROM `login`.`commenttable` WHERE `commenttable`.`id` = ?";
    $deleteComment = "DELETE FROM commenttable WHERE id = ?";
    if ($stmt = mysqli_prepare($connection, $deleteComment)) {
        mysqli_stmt_bind_param($stmt, "s", $commentId);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
    } else {
        echo "error";
    }
}
?>

最佳答案

您没有在函数中设置$connection变量。如果启用了错误报告功能,则会看到有关未定义变量正在使用的警告。

我假设它是在connect.php中设置的,但是全局变量在函数内部不可见。您要么将它作为函数的参数传递:

DeleteRowFunction($connect, $_POST['commentId']);
...
function DeleteRowFunction($connection, $commentId) {
    ...
}


或者您需要将global $connection;放在DeleteRowFunction()的开头。

10-07 17:31