Jayprakash Sharma
Jayprakash Sharma

Reputation: 3

Database query not working in WordPress template page

Totally New to WordPress and I keep seeking answers as why is the same code that totally works is not working in WordPress.

$arr = array();
if (!empty($_POST['keywords'])) {
    $keywords = $db->real_escape_string($_POST['keywords']);
    $sql = "SELECT result_id, end_home_odd, home_name FROM tbl_live WHERE home_name LIKE '%".$keywords."%'";
    $result = $db->query($sql) or die($mysqli->error);
    if ($result->num_rows > 0) {
        while ($obj = $result->fetch_object()) {
            $arr[] = array('id' => $obj->result_id, 'home' => $obj->end_home_odd, 'title' => $obj->home_name);
        }
    }
}
echo json_encode($arr);

And in WordPress template page, tried this:

$arr = array();
if (!empty($_POST['keywords'])) {
    $keywords = $_POST['keywords'];
    $sql = $wpdb->get_results("SELECT result_id, end_home_odd, home_name FROM tbl_live WHERE home_name LIKE '%".$keywords."%'");
    $result = $db->query($sql) or die($mysqli->error);
    if (count($result) > 0) {
        while ($obj = $result->fetch_object()) {
            $arr[] = array('id' => $obj->result_id, 'home' => $obj->end_home_odd, 'title' => $obj->home_name);
        }
    }
}
echo json_encode($arr);

What am I missing that it won't work in WordPress? Can someone shed light on this?

Upvotes: 0

Views: 432

Answers (1)

Sally CJ
Sally CJ

Reputation: 15620

Here it is the WordPress way:

$arr = array();
if (!empty($_POST['keywords'])) {
    $keywords = $_POST['keywords'];

    // Properly escapes the POST data.
    $like = '%' . $wpdb->esc_like( $keywords ) . '%';
    $sql = $wpdb->prepare( "SELECT result_id, end_home_odd, home_name FROM tbl_live WHERE home_name LIKE %s", $like );

    $result = $wpdb->get_results( $sql );
    if ( ! empty( $result ) ) {
        foreach ( $result as $obj ) {
            $arr[] = array('id' => $obj->result_id, 'home' => $obj->end_home_odd, 'title' => $obj->home_name);
        }
    }
}
echo json_encode($arr);

Tried and tested with WordPress 4.9.4.

Upvotes: 1

Related Questions