Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the $wpdb in wordpress to run SQL commands

I created a simple update command to update a database entry. I want to be able to run any sql statement and update my wordpress database:

<?php    
global $wpdb;
$sql = "UPDATE tablename SET column1='testdata' WHERE id=1";
$results = get_results($sql); ?>

or

$results = query($sql);

No matter what I do I get the error:

Fatal error: Call to a member function get_results() on null in C:\MAMP\htdocs\new\samplesql.php on line 4

like image 371
GRS Avatar asked Feb 22 '17 23:02

GRS


People also ask

What is the $Wpdb variable in WordPress?

The $wpdb object can be used to read data from any table in the WordPress database, not just those created by WordPress itself.

How do I interact with WordPress database?

WordPress provides a set of functions to interact with databases using the $wpdb object. Since it's a global object you can call this function anywhere using global declaration. global $wpdb; You can see a full explanation of wpdb on the WordPress codex site.


2 Answers

Try this instead:

<?php    
include_once("wp-config.php");
include_once("wp-includes/wp-db.php");

$sql = "UPDATE tablename SET column1='testdata' WHERE id=1";
$results = $wpdb->get_results($sql);

You need to include the files where the database object is defined.

like image 169
miken32 Avatar answered Sep 20 '22 19:09

miken32


The get_results() and query() functions only work when combined with the $wpdb global.

For example:

global $wpdb;
$wpdb->get_results($sql);
like image 35
GerritElbrink Avatar answered Sep 17 '22 19:09

GerritElbrink