【问题标题】:Writing results of database query to text file with PHP使用 PHP 将数据库查询结果写入文本文件
【发布时间】:2016-10-04 22:07:06
【问题描述】:

我编写了一些代码,用于在我的 wordpress 网站的帖子表中提取附件。

第一个函数会下拉结果,但我无法将其写入文本文件。

文件的创建很好,我没有收到任何错误。代码正在运行,我只是没有收到日志。我想知道它准备移动哪些文件。

这是我的插件中有问题的功能

function getPostsToMove($baseurl){  

    $baseurl = $baseurl.'/%/%/%.%'; 
    $myfile = fopen("/websites/site.dev/wp-content/uploads/newfile.txt", "w") or die("Unable to open file!");

    global $wpdb  ;

    return $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE `guid` not 
    like '$baseurl' and `post_type` = 'attachment' ORDER BY post_date DESC LIMIT 1000");

    fwrite($myfile, $baseurl);
    fclose($myfile);
}

我错过了什么?

编辑-我的顺序错了。下面这些是对的。但显然我没有从我的回报中获取数据。我需要把它变成一个数组吗?

新代码

function getPostsToMove($baseurl){  

$baseurl = $baseurl.'/%/%/%.%'; 
    $myfile = fopen("/websites/site.dev/wp-content/uploads/newfile.txt", "w") or die("Unable to open file!");

    fwrite($myfile, $output);
    fclose($myfile);
    global $wpdb;  
    $output = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE `guid` not 

like '$baseurl' and `post_type` = 'attachment' ORDER BY post_date DESC LIMIT 1000");

return $output;

}

【问题讨论】:

  • return 表示返回...return 之后没有执行任何操作
  • 是的,试试在函数末尾加上return
  • 这只是收集要移动的文件的第一个函数,如何在查询发生之前写入和关闭文件?
  • 为了记录,我试过了,只是为了确定。它没有写任何东西。但插件有效。
  • 我的意思是,也许这是正确的顺序,但我没有获取返回的数据。我不知道。我以前没有这样做过。

标签: php sql wordpress


【解决方案1】:

您的函数似乎在尝试写入文件后检索查询。

您似乎计划检索数据,将其写入文件,然后返回数据以供您的应用程序进一步使用,我建议如下。

function getPostsToMove($baseurl){  
    $baseurl = $baseurl.'/%/%/%.%';
    $myfile = fopen("/websites/site.dev/wp-content/uploads/newfile.txt", "w") or die("Unable to open file!");

    // Query the data and assign the variable before writing
    global $wpdb;
    $results = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE `guid` not like '$baseurl' and `post_type` = 'attachment' ORDER BY post_date DESC LIMIT 1000");

    // json_encode() to turn the retrieved array into a JSON string for writing to text file
    $output = json_encode($results);

    // write the file
    fwrite($myfile, $output);
    fclose($myfile);

    // return the result (array) for further use in application
    return $results
}

【讨论】:

  • json_encode() 是使数组写入文本文件的一种方法。当然,您可以将信息解析为更易读的方式并相应地编写。但这超出了这个问题的范围
  • 谢谢!这就是我所缺少的。实际的解析和输出。如果您有该主题的链接或资源,我想学习更好的方法。知道未来会很好。
  • this 这样的东西看起来是一个很好的资源,可以深入研究将数组转换为“人类可读”格式。
猜你喜欢
  • 1970-01-01
  • 2017-11-01
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多