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.

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

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,