简体   繁体   中英

Is it possible to write the result of a $WPDB query in file

I like to be able to write the query result to a file... now this code write ARRAY... useless !

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;

After changing fwrite to file_put_contents that fix the problem.... so here is the solution

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));

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

Before:

ob_start()

After "/table"

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

Is that you want?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM