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.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化