Add custom php database code above

You could use a WordPress action hook. For example, you could add the following code to your themes functions.php file:

add_action( 'init', 'your_script_function' );

function your_script_function() {
    // your script here
}

The first line makes WordPress execute the ‘your_script_function’ function on initialization. You can add your script in that function.

Alternatively, you could add the code to a plugin. This would be easier for using/installing the script on multiple WordPress installations. It is indeed not recommended to edit the WordPress core files.

For more information about WordPress actions and hooks: