这是我使用的代码:
<?php
// declare the variables for access
// database to be exported
$db = 'BLANK';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'db_export_'.$db.'_'.date('Y-m-d').'.csv';
// database variables
$hostname = "BLANK";
$user = "BLANK";
$password = "BLANK";
$database = "BLANK";
$port = BLANK;
$conn = mysqli_connect($hostname, $user, $password, $database, $port);
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysqli_query($conn, "SELECT * FROM ".$db." ".$where);
$field = mysqli_field_count($conn);
// create line with field names
for($i = 0; $i < $field; $i++) {
$csv_export.= mysqli_fetch_field_direct($query, $i)->name.';';
}
// newline
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysqli_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";';
}
$csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>
它并没有真正给我我预期的结果,而是生成一个包含表信息的csv文件,如:
(!)警告:mysqli_fetch_array()需要参数 1是mysqli_result布尔值 C:\ wamp64 \ www \ cronjob \ TestJob1.php在线路上 33 呼叫堆栈
#TimeMemoryFunctionLocation 10.0145244752 {main}()... \ TestJob1.php : 0 20.1295255904http://www.php.net/function.mysqli-fetch-array' target =&#39; _new&#39;&gt; mysqli_fetch_array()... \ TestJob1.php : 33
在csv中以不同的格式出现,涉及奇怪的表行/列和颜色声明。我确实不确定确切的错误,因为我的第33行只是一个评论,我非常感谢任何帮助。用户名和密码等信息会被故意删除。
答案 0 :(得分:1)
您的WHERE子句和ORDER BY子句是错误的。你实际上并没有将它与任何东西进行比较。
WHERE somecolumn = "somevalue" ORDER BY somecolumn