duanji9677 2014-06-13 14:06
浏览 113
已采纳

在WordPress中读取sql文件

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.

  • 写回答

1条回答 默认 最新

  • doutiaoku4495 2014-06-13 14:49
    关注

    Let's first start debugging the file path issue. There are two things you can use here.

    function db_data() {
        WP_Filesystem();
        global $wp_filesystem;
        global $wpdb;
        echo 'Current Path is '. __DIR__;
        $file =  __DIR__."/sql/my_insert_query.sql";
        if(!is_readable($file)) {
            echo 'File not found or not readable '.$file;
        }     
        $table_name = $wpdb->prefix . "tableName";
    
        $sql_insert = "INSERT INTO $table_name (id, something) ";
        $sql_insert .= $wp_filesystem->get_contents( $file );
        $rows_affected = $wpdb->query( $sql_insert );
    }
    

    That will at least provide more insight about the filepath.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!