1

I am trying to query a mysql database and display data in a table.I now want to take the table and make a button that allows you to export it to an excel file.now you were able to export to excel,but its showing an error Notice: Undefined variable: data

Below is my code:

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "export";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");

$values =mysql_query( "SELECT name,email,phone,nationality,dob FROM users order by id");

$header = "Name" . "\t";
$header .= "Email" . "\t";
$header .= "Phone" . "\t";
$header .= "Nationality" . "\t";
$header .= "DOB" . "\t";

while( $row = mysql_fetch_assoc($values)){
$row1 = array();


$row1[] = $row['name'];
$row1[] = $row['email'];
$row1[] = $row['phone'];
$row1[] = $row['nationality'];
$row1[] = $row['dob'];

$data .= join("\t", $row1)."\n";
   }
header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=expot.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data"; 
exit(); 
?>
4
  • Move your initialisation of $row1 = array(); outside of the foreach loop Commented Dec 24, 2013 at 8:09
  • @MarkBaker thanks but all the value showing in same line ,not showing one by one Commented Dec 24, 2013 at 8:13
  • Then move your headers above the while loop, and try using PHP's built-in fputcsv() function to create your file to php://output rather than building up all this data in memory Commented Dec 24, 2013 at 8:15
  • can you please modify my code Commented Dec 24, 2013 at 8:21

2 Answers 2

3

Because you never initialize the $data variable.

Put:

$data = '';

at the beginning of your code, before the while cycle.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks ,now error is not displaying,but it only taking the last value in the html table ,not taking the all data
2

Your code contains the statement:

$data .= join("\t", $row1)."\n";

This is where you're concatenating a string to an existing variable $data. However, no such variable exists. You should add somewhere near the top of your code:

$data = "";

to initialize the $data variable.

2 Comments

thanks ,now error is not displaying,but it only taking the last value in the html table ,not taking the all data
Are you sure you put the $data = "" outside the while loop?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.