I'm trying to populate a database table by reading some sql from a file.sql and putting it into a string before calling the query. But I seem to be unable to load the file into a string. What gives?
function db_data() {
WP_Filesystem();
global $wp_filesystem;
global $wpdb;
$table_name = $wpdb->prefix . "tableName";
$file = "/sql/my_insert_query.sql";
$sql_insert = "INSERT INTO $table_name (id, something) ";
$sql_insert .= $wp_filesystem->get_contents( $file );
$rows_affected = $wpdb->query( $sql_insert );
}
The $sql_insert turns out as an empty string. What am I doing wrong here?
EDIT:
Found the way to get to the right directory path. This is the finished code:
function db_data() {
WP_Filesystem();
global $wp_filesystem;
global $wpdb;
$table_name = $wpdb->prefix . "tableName";
$sql_insert = "INSERT INTO $table_name (id, something) ";
$dir = plugin_dir_path( __FILE__ );
$file = $dir."/sql/my_insert_query.sql";
$sql_values = $wp_filesystem->get_contents( $file );
$sql_insert .= $sql_values;
$rows_affected = $wpdb->query( $sql_insert );
}
For the answer on finding and reading the sql file. Check the answer below.