Set Featured Image Based on Custom Field

global $wpdb;
$children = get_posts('post_type=event&numberposts=1');
foreach ($children as $child) {
    $origParentID = get_post_meta($child->ID, 'mainpictureid', true);
    $parsed_url  = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), 'http://localhost/wp-content/uploads/2015/08/'.$origParentID.'.jpg' );
    $attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );
    set_post_thumbnail( $child->ID, $attachment[0]); 
}