Converting MYSQL to WordPress $WPDB

The root problem here is the assumption that WordPress deals in mysql functions and mysql objects, and that knowledge of these functions is helpful.

The truth is, this is a complete API in of itself, and so the assumptions that knowledge of mysql_ functions provides are not useful or relevant beyond the syntax of SQL.

For example:

$result = $wpdb->query ( $sql ) or die('Content was not loaded.');
$counter = 0;
while($post = mysql_fetch_array($result)) {

Here the assumption is that $wpdb->query returns a results object, but that is not true.

If we look at what query actually returns by looking at the examples in the documentation we can see:

This function returns an integer value indicating the number of rows affected/selected

And that:

If a MySQL error is encountered, the function will return FALSE. Note that since both 0 and FALSE may be returned for row queries, you should be careful when checking the return value.

So How Do I Fetch Rows?

Using get_results:

$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );

Don’t forget to run your SQL statement through $wpdb->prepare first to prevent injection attacks!

There are other methods that allow you to fetch a singular value, row, or column, but here $myrows is literally an array with the rows selected ( or an error response ). There is a second parameter to get_results that determines the return type, e.g. an associative array, an object with keys, etc

https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results

The Problem of Your Second and Third Queries

Even if you fix these queries, they are fundamentally bad practice, because they have a faster, trivial replacement:

$value = get_post_meta( $post_id, 'key' );

$value now contains all the meta values for that post with the meta key key.

You can also use WP_Query to fetch posts via their meta keys and values ( but be warned, this is a cardinal sin for performance wether you use the API, or a direct SQL )

There’s probably an ACF function or API that can replace the direct SQL query in the beginning. It’s very rare that you should need to do a direct SQL query. In my day job I review code for major websites handling billions of page views, and millions of lines of code, of which I’ve encountered direct SQL queries only a handful of times