【问题标题】:Query working on phpmyadmin but not in php script查询在 phpmyadmin 上工作但不在 php 脚本中
【发布时间】:2021-03-18 11:43:15
【问题描述】:

我已经尝试过类似问题的其他解决方案,但似乎没有任何效果。就像标题所说,我需要在我的数据库上执行的查询在 phpMyAdmin 上运行良好,但在 php 函数中使用时它不起作用。这是 common_functions.php 中的代码:

function eliminaRistorante($id_ristorante) {
    global $conn;

    // query su ristorante
    $sql = "DELETE FROM ristorante WHERE id_ristorante = $id_ristorante";

    echo $sql;

    if($conn->query($sql) === TRUE) {
        return true;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        return false;
    }
}

这是hold.php中的代码:

include('includes/logic/common_functions.php');

if (isset($_POST['del'])) {
    $id_ristorante = $_POST['del'];

    eliminaRistorante($id_ristorante);
    header('location: admin/ristorante.php');
}

我放了一个 echo 语句来查看查询是否有效。 这是输出:

从 ristorante 中删除其中 id_ristorante = 5 致命错误:未捕获的错误:在 C:\xampp\htdocs\projects\db_ristorante\includes\logic\common_functions.php:57 调用成员函数 query() on null 堆栈跟踪:#0 C:\xampp\htdocs\projects \db_ristorante\hold.php(8): eliminaRistorante('5') #1 {main} 在第 57 行的 C:\xampp\htdocs\projects\db_ristorante\includes\logic\common_functions.php 中抛出

最后,我尝试了以下解决方案: MySql query not in working in PHP but works in phpMyAdmin

在该问题中,用户友好地分享了我也考虑过的其他解决方案。

【问题讨论】:

  • Call to a member function query() on null 并不表示您的查询有问题,而是表示$conn 为空。
  • 最好将$conn 作为参数传递到您的函数中,而不是使用全局变量。此外,您需要查看准备好的语句,而不是将字符串连接到查询中。
  • 多亏了这两个我得到了错误弹出的原因,我按照@droopsnoot 的建议做了,并将 $conn 作为参数传递,解决了问题。

标签: php mysql


【解决方案1】:

未捕获的错误:在 null in 上调用成员函数 query()

您的 $conn 对象为空。您没有初始化 PDO 实例。

这是一个介绍,关于如何做到这一点,PHP The Right Way - PDO

【讨论】:

    猜你喜欢
    • 2014-09-07
    • 2019-02-09
    • 2015-05-17
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2013-03-14
    相关资源
    最近更新 更多