是否可以在文件中写入$ WPDB查询的结果

时间:2013-11-30 23:46:13

标签: wordpress file wpdb

我希望能够将查询结果写入文件...现在这段代码写了ARRAY ......没用!

global $wpdb;

$wpdb->show_errors();

//insert in DB
$randomString = '"'.substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand()).'"';
$randnum = rand(1,999);
$wpdb->query("INSERT INTO test (id,tx) VALUES($randnum,$randomString)");

//read DB
$queryResult = $wpdb->get_results("SELECT * FROM test ");
$i=1;
echo "<table>";
foreach($queryResult as $subQuery){
echo "<tr>";
echo "<td>".'['.$i.'] '.$subQuery->id.' '.$subQuery->tx."</td>";
echo "</tr>";
$i++;
}
echo "</table>";

//write file
$filename = 'aaaa.txt';
$handle = fopen($filename, 'a');
$filewrite = fwrite($handle,$queryResult);
echo $filewrite;

3 个答案:

答案 0 :(得分:0)

将fwrite更改为修复问题的file_put_contents后....所以这是解决方案

global $wpdb;

$wpdb->show_errors();
//$wpdb->print_error();

//insert in DB
$randomString = '"'.substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand()).'"';
$randnum = rand(1,999);
$wpdb->query("INSERT INTO test (id,tx) VALUES($randnum,$randomString)");

//read DB
$queryResult = $wpdb->get_results("SELECT * FROM test ");
$i=1;
echo "<table>";
foreach($queryResult as $subQuery){
echo "<tr>";
echo "<td>".'['.$i.'] '.$subQuery->id.' '.$subQuery->tx."</td>";
echo "</tr>";
$i++;
}
echo "</table>";

//write file
$filename = 'aaaa.txt';
//$handle = fopen($filename, 'w');
$json = json_encode($queryResult);
//$filewrite = fwrite($handle,$queryResult);
//fclose($handle);

file_put_contents ($filename,$json);

//read it back : 
$myarray = json_decode(file_get_contents($filename));

答案 1 :(得分:0)

如果仅用于缓存,那么除了所有其他类型的缓存外,您还可以选择W3总缓存插件,它也提供数据库缓存。

答案 2 :(得分:-1)

在:

ob_start()

在“/ table”之后

$data = ob_get_contents();
//...
fwrite($handle, $data);

你想要的吗?