17

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

3 Answers 3

26

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, it works for me too. I'm surprised I didn't find this mentioned in the function documentation. Anyway thanks a lot!
I did a lot of research to find an easy way and code that really works. The code you wrote is great and works well. My WordPress is version 6
12

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

For example:

global $wpdb;
$wpdb->get_results($sql);

Comments

0

Here is a complete Example.

global $wpdb;
$sql = 'SELECT p.post_title FROM wp_posts as p WHERE p.post_status = %s';
$vars = ['publish'];
$result = $wpdb->get_results( $wpdb->prepare($sql, $vars) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.