In wordpress I am querying the default table for custom rows and columns that I have manually added. I am globalizing the $wpdb
(WordPress database function) and it works for half of the code.
For example the first part of the script is like so (only showing relevant parts of the code):
class Test {
public function getP($param){
global $wpdb;
$q = $wpdb->get_results("SELECT * FROM tbl WHERE " . $param['1']." = '" . $param['2'] . "'");
}
}
So that query works when running through $wpdb
and I am able to print the results that get returned.
However, further down I then need to run another query based on results, so instead of $wpdb->get_results
i need to use $wpdb->query
.
Example (again, only the relavant):
global $wpdb;
$stmt = $this->wpdb->query($q);
if($param['type'] == 'x'){
$data = $stmt->fetchAll();
}else{
$data = $stmt->fetch();
}
return $data;
That does not work, intead it seems to fall outside of the object and provide the following error:
Fatal error: Call to a member function query() on a non-object
Any insight as to why the initial query works but than the second query results in an error, even though the database connection works and is inside of the object?
From the docs:
From here
The
$wpdb->query()
method does not return the result, it returns the number of effected rows. If you want to have the result use$wpdb->get_results()
for instance, but probably one of the other methods does fit better to your needs.That is why you get the
FatalError
, because the Integer is not an Object.Have a look here at the
$wpdb
reference there every method is explained quite well.Good Luck!
In your example, you are trying to run a
$wpdb->query
against astdClass array()
or results, not an SQL query.$wpdb->get_results
will return an object/array of rows, not another query-able SQL statement like you were hoping. You ultimately could write a control loop that would generate your new SQL statement.