$wpdb->insert() is giving error undefined function

2019-02-20 03:12发布

问题:

I have created a new file inside wp-content/theme/mytheme folder.

Inside the file I have written simple query

global $wpdb;
    $insert= $wpdb->insert('wp_test', array(
    'orderID' =>$_GET['orderID'],'amount'=>$_GET['amount'],'acceptance'=>$_GET['ACCEPTANCE'],'status'=>$_GET['STATUS'],
    ));

I am getting error "Call to undefined function". Do I have to include file inside this file?

回答1:

Try this : include wp-load.php at beginning of file.

File is located at theme folder.

require_once('../../../wp-load.php');    //<-----please include this

global $wpdb;
    $insert= $wpdb->insert('wp_test', array(
    'orderID' =>$_GET['orderID'],'amount'=>$_GET['amount'],'acceptance'=>$_GET['ACCEPTANCE'],'status'=>$_GET['STATUS'],
    ));


回答2:

According to this document : https://codex.wordpress.org/Class_Reference/wpdb

you must change your code to this:

global $wpdb;
$wpdb->insert(
  'wp_test',
  array(
    'orderID' => $_GET['orderID'],
    'amount' => $_GET['amount'],
    'acceptance' => $_GET['ACCEPTANCE'],
    'status' => $_GET['STATUS'],
  ),
  array( '%d', '%d', '%s','%s' )

);


回答3:

By these ways , You can do it easily,

First define $wpdb globally as like global $wpdb;

require_once('../wp-load.php'); // relative path

<?php
$wpdb->insert("wp_submitted_form", array(
   "col_nmae" => $value,
 ));
?>

Second Way is

$sql = $wpdb->prepare(
    "INSERT INTO `wp_submitted_form`    
       (col_nmae) 
 values ($val)");
$wpdb->query($sql);

Third is

$sql = "INSERT INTO `wp_submitted_form`
          (col_nmae) 
   values ($val)";

$wpdb->query($sql);

If you are beginner then read more here https://codex.wordpress.org/Class_Reference/wpdb



标签: wordpress