SQL/WordPress/AJAX : Format JSON With Loop

PROBLEM

I’m trying to query my database (wp_usermeta table) and export it in a JSON format to be processed by an autocomplete plugin. I need the data to be formatted as such:

Read More
{"suggestion":"copmany1", "umeta_id":"1"},{"suggestion":"company2", "umeta_id":"2"}, etc.

SO FAR

My current code outputs the info as such:

{"suggestions":["concept9 test","Company"],"data":["58","77"]}

This is my code:

$query = $_GET["query"];



    // escape values passed to db to avoid sql-injection
    $query = $wpdb->get_results( "SELECT DISTINCT umeta_id, meta_value FROM wp_usermeta WHERE meta_key='company' AND meta_value LIKE '".$query."%' order by umeta_id" );

    $suggestions = array();

    foreach($query as $row) {
        $suggestions[] = $row->meta_value;
        $data[] = $row->umeta_id;

        $response1 = array(
        'suggestions' => $suggestions,
        'data' => $data,
    );
    }


    $response = json_encode( $response1 );
    echo $response;
    exit();

Thanks!

Related posts

1 comment

  1. Try it like this:

    $query = $_GET["query"];
    // escape values passed to db to avoid sql-injection
    $query = $wpdb->get_results( "SELECT DISTINCT umeta_id, meta_value FROM wp_usermeta WHERE meta_key='company' AND meta_value LIKE '".$query."%' order by umeta_id" );
    $suggestions = array();
    foreach($query as $row) {
        array_push($suggestions, array(
                'suggestion' => $row->meta_value,
                'umeta_id' => $row->umeta_id
            )
        );
    }
    echo json_encode( $suggestions );
    exit();
    

    Comment here if you need further explanation

Comments are closed.