Using the WordPress $wpdb class to read the MySQL database to do AJAX problems in how to solve _ajax related

Source: Internet
Author: User

Bored to do a www.jiazhuangma.com, technology does not pass through the background, want to read the data directly in WordPress. Do Ajax read the background data on the Internet casually searched a section of code to use WordPress $wpdb class to read MySQL database, is so casually, found someone else's head to the end of the code, began my mistake trip.

The main problems are:

1,non-object

Chinese characters in 2,json,/by transcoding

3,chrome can normally access the PHP file, ie display HTTP 404,ajax when the head display 404, but the response body is correct, is the JSON I want.

First put the code found on the Internet:

<?php
global $wpdb;
$a = $wpdb->get_results ("Select Id,post_title from Wp_posts″");
echo Json_encode ($a);
? >

At this time will be an error, non-object;

Some people on the internet say that they can add require_once (' wp-blog-header.php '); So congratulations on your winning, you'll find that chrome can normally access PHP files, ie display HTTP 404,ajax when the head display 404, but the response body is correct.

Modified to require_once (' wp-config.php ');

The resulting JSON is the transcoding after the need for the Echo json_encode ($a);

Modified to echo str_replace ("\\/", "/", Json_encode ($a, json_unescaped_unicode)); The results are correct.

Final Result:

<?php
require_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 wp_term_relationships.object_id DESC LIMIT 5″);
Echo str_replace ("\\/", "/", Json_encode ($a, json_unescaped_unicode));
? >

The above is a small series to introduce the use of WordPress $wpdb class to read MySQL database to do AJAX problems in how to solve the problem, I hope to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.