【问题标题】:SQL INSERT query fails to executeSQL INSERT 查询无法执行
【发布时间】:2021-11-02 21:07:33
【问题描述】:

我有一个名为“species”的表,包含 3 列:id、specie、rate。

我已经尝试使用以下查询,但它会引发错误:

Fatal error: Uncaught Error: Call to a member function insert() on null in D:\Wordpress\....includes\specie_form.php on line 10

Error: Call to a member function insert() on null in D:\Wordpress.....includes\specie_form.php on line 10

查询

$specie_name= $_POST['specie_name'];
$specie_rate=$_POST['specie_rate'];

    global $wpdb;
    
    $wpdb->insert('species', array( //this is line 10 of error
        'id' => NULL,
        'specie' => '$specie_name',
        'rate' => '$specie_rate'
    ));

这就是我的数据库的样子:

【问题讨论】:

  • 我没有看到分配给$wpdb
  • @Serg 你能看看我下面的解决方案,看看这是否是分配 wpdb 的理想方式,即通过if(!isset($wpdb)) { require_once('../../../../wp-config.php'); require_once('../../../../wp-includes/wp-db.php'); }

标签: sql wordpress


【解决方案1】:

看起来在表格种类中,您不能将 null 作为有效值输入到 id 列。

查看表中列 id 是否可以为空 并试着给他一个号码

如果有自动增加选项,请尝试不带 id 列的插入

$wpdb->insert('species', array(
    'specie' => '$specie_name',
    'rate' => '$specie_rate'
));

这不是查询的问题,而是你如何访问 wpdb 看看

Call to a member function insert() on null WORDPRESS

【讨论】:

  • 谢谢,但仍然是同样的错误:致命错误:未捕获错误:在 null 上调用成员函数 insert() ... 错误:在 null 上调用成员函数 insert() .. .
  • 抱歉,问题似乎不在于 SQL 本身,而在于您如何在页面或插件中使用 wpdb,请参阅stackoverflow.com/questions/29919151/…
  • 我不同意附加的链接内容,因为建议“仅”在插件中使用 wpdb 而不是直接在 php 页面上使用。然而,在这个...youtube.com/watch?v=gNnf2rRDWEw&t=470s...video 中,他直接在一个名为 wpdb.php 的主题文件中运行它。
  • 好吧,我不是 wordpress / php 专家,只知道这里的 SQL,但如果你没有复制它,它可能是
【解决方案2】:

好的,所以我设法通过包含一些需要的文件来解决问题,如下所示:

 global $wpdb;

    if(!isset($wpdb))
        {
            require_once('../../../../wp-config.php');
            require_once('../../../../wp-includes/wp-db.php');
        }

    $wpdb->insert('species', array(
        'specie' => $specie_name,
        'rate' => $specie_rate
    ));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多