Site icon Hip-Hop Website Design and Development

Error in SQL Syntax

Below is my code to check if ticket_id and Msgno are same and if they are not same perform wp_insert_post

global $wpdb;
//Get all emails. 
$total =  $emails->total_msg(); 
    for ($j=1; $j <= $total; $j++) { 
       $mail =  $emails->get($j);
       $query = $wpdb->prefix."postmeta";
       $no = $mail['header']->Msgno;
       $q = "SELECT * FROM $query where meta_key = 'ticket_id' and meta_value=' ".$no." ' ";
       $result = $wpdb->get_results($q);
       $wpdb->query( $query );

    if ( $wpdb->num_rows ) {
        $post_id = $wpdb->get_var( $query );
        $meta = get_post_meta( $post_id, 'ticket_id', TRUE );
        $meta++;
        update_post_meta( $post_id, 'ticket_id', $meta );
    } 
    else {
       $post_array = array( 
        'post_content'  => $mail['body'],
        'post_title'    => $mail['header']->subject,
        'post_type'     => 'faqpress_email',
        'post_status'   => 'publish',
        'meta_input'    => array(
            'from'      => $mail['header'] ->fromaddress,
            'email_date'=> $mail['header'] ->Date,   // add post meta as many as you want
            'ticket_id' => $mail['header']->Msgno,
            ),);
    wp_insert_post($post_array);
    }
}

I am getting the following error:

WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘wp_postmeta’ at line 1] wp_postmeta

Not only do I want to learn about how to solve this error or what mistake I am doing with my code. I also want to know that my code works for what I want to achieve?