将数据导出到csv后出现未定义的变量错误[关闭]
i try to learn how to export data to csv using this script, yes i can export all data but in csv i found one error(when run in localhost) :
<b>Notice</b>: Undefined variable: csv_output in <b>C:\xampp\htdocs\import_export\index.php</b> on line <b>10</b><br />
not sure why, but i can run this code in live server without any issue.
Full code
error_reporting(E_ALL);
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("csv") or die(mysql_error());
$file = "product_export"; // csv name.
//CSV Header
$csv_output .= "ID " . ", ";
$csv_output .= "Content " . ", ";
$csv_output .= "
";
//CSV Content rows
$query = mysql_query("SELECT * FROM `users`");
while ($row = mysql_fetch_array($query)) {
$csv_output .= $row["id"] . ", ";
$csv_output .= $row["content"] . ", ";
$csv_output .= "
";
}
$filename = $file . "_" . date("d-m-Y_H-i");
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=" . $filename . ".csv");
print $csv_output;
exit;
p/s : im using mysql_* for testing only.
PHP is just letting you know that you are using a variable that hasn't been defined yet. It's a notice, not a warning or error.
This line is prompting the notice:
$csv_output .= "ID " . ", ";
It's the first use of this variable, you don't need concatenation at this point. Easy fix would be to change it to:
$csv_output = "ID " . ", ";
If you don't want PHP spitting out notices, you could change the first line of your script to:
error_reporting(E_ALL ^ E_NOTICE);
In the first line:
//CSV Header
$csv_output .= "ID " . ", ";
You're trying to Concatenate the id to the variable, but the variable was never defined.
The first time you use a variable don't use the dot in front of the 'equals sign' so try this:
In the first line:
//CSV Header
$csv_output = "ID " . ", ";
Appending variables with .=
required your to declare the variable in its proper form first, like: $variable = $value
then you can append it, otherwise it will give you always undeclared variable error.