How can I solve the problem when I use wordpress's $ wpdb class to read mysql database for ajax? wordpresswpdb
I am bored with www.jiazhuangma.com. I want to directly read the data in wordpress if the technology is not well-written in the background. When I used ajax to read background data, I randomly searched a piece of code on the Internet and used wordpress $ wpdb to read mysql databases. That's exactly what I found, I started my mistake correction journey.
Main problems:
1, non-object
2. Chinese Characters in json,/transcoded
3. chrome can access the PHP file normally. ie shows http 404, while ajax displays 404 in the header, but the response body is correct, which is the json I want.
First paste the code found on the Internet:
<?phpglobal $wpdb;$a = $wpdb->get_results(“SELECT ID,post_title FROM wp_posts ″);echo json_encode($a );?>
At this time, an error is reported, non-object;
Someone on the Internet said you can add require_once ('wp-blog-header.php '); So congratulations, you will find that chrome can access the PHP file normally, ie shows http 404, ajax when the header shows 404, however, the response body is correct.
Change to require_once ('wp-config. php'); and then it will be normal,
In this case, after transcoding, The json file needs to echo json_encode ($ );
Modify it to echo str_replace ("\/", "/", json_encode ($ a, JSON_UNESCAPED_UNICODE). The result is correct.
Final result:
<?phprequire_once(‘wp-config.php');global $wpdb;$a = $wpdb->get_results(“SELECT wp_posts.ID,wp_posts.post_title,wp_posts.guid FROM wp_posts inner join wp_term_relationships on wp_term_relationships.object_id=wp_posts.ID where wp_term_relationships.term_taxonomy_id=3 ORDER BY wp_term_relationships.object_id DESC LIMIT 5″);echo str_replace(“\\/”, “/”, json_encode($a,JSON_UNESCAPED_UNICODE ));?>
The above section describes how to solve the problem of using wordpress $ wpdb to read mysql database for ajax. I hope it will be helpful to you.