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
The $wpdb object can be used to read data from any table in the WordPress database, not just those created by WordPress itself.
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.
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.
The get_results() and query() functions only work when combined with the $wpdb global.
For example:
global $wpdb;
$wpdb->get_results($sql);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With