如何在MySQL中创建临时表以将表数据输出为CSV文件?
我有一个用于从数据库表创建 CSV 文件的脚本,该脚本运行良好,只是它输出表中的所有数据,并且我需要它仅输出当前登录用户的数据。我正在开发的应用程序是为了让用户能够存储他们已读过、想要阅读等的书籍列表,我希望能够允许他们下载可以导入 Excel 的书籍列表例如。 (考虑到还有 OpenOffice 等以及 MS Excel,CSV 文件是否是最佳选择?)
我发现我需要创建一个临时表来使用选择查询来仅选择属于当前的记录已登录的用户。我可以使用 WHERE username='$session->username'
访问当前用户的数据。
我认为这就像在尝试运行输出数据以在 CSV 文件中使用的查询之前创建临时表一样简单,然后删除该表,但我已经使用临时表再次尝试了 CSV 创建代码在 CSV 内容之前创建的表,生成的 CSV 文件再次包含所有用户的所有记录。
有一个配置文件设置数据库连接属性,还有用于创建文件的表,作为变量 $table
,我已将其设置为临时表的名称我正在努力创造。
这是我得到的代码:
<?
$link = mysql_connect($host, $user, $pass) or die("Cannot connect to the database." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$temp = mysql_query("CREATE TEMPORARY TABLE books_temp SELECT * FROM books WHERE username='$session->username'");
$tempresult = mysql_query($temp);
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("d-m-Y") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
$query = 'DROP TABLE books_temp';
$result = mysql_query($query);
exit;
?>
它可以完美地输出所有数据,但当我尝试将其与临时表一起使用时,仍然输出所有数据。顺便说一句,我也尝试删除从末尾删除临时表的指令,但这没有任何区别。另外,检查 PhpMyAdmin,似乎没有创建临时表。我显然在这里做错了什么或者遗漏了一些东西,但我不知道是什么。
I've got a script for creating a CSV file from a database table, which works fine except that it outputs all the data in the table, and I need it to output data only for the current logged in user. The app I'm developing is for users to be able to store lists of books they've read, want to read, etc., and I want to be able to allow them to download a list of their books they can import into Excel for example. (Would a CSV file be the best option for this, given that there's also OpenOffice etc. as well as MS Excel?)
I figured out that I needed to create a temporary table to use a select query to select only records belonging to the current logged-in user. I can access the data for the current user using WHERE username='$session->username'
.
I thought it would be as easy as creating the temporary table before I try to run the queries that output the data for use in the CSV file, and then drop the table afterwards, but I've tried the CSV creation code again with the temporary table created before the CSV stuff, and again the CSV file produced includes all the records for all users.
There's a configuration file that sets the database connection properties, but also the table to be used to create the file, as the variable $table
, and I've set this to be the name of the temporary table I'm trying to create.
This is the code I've got:
<?
$link = mysql_connect($host, $user, $pass) or die("Cannot connect to the database." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$temp = mysql_query("CREATE TEMPORARY TABLE books_temp SELECT * FROM books WHERE username='$session->username'");
$tempresult = mysql_query($temp);
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("d-m-Y") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
$query = 'DROP TABLE books_temp';
$result = mysql_query($query);
exit;
?>
It works perfectly outputting all the data, but still outputs all the data when I try to use it with the temporary table. Incidentally, I've tried remove the instruction to drop the temporary table from the end as well, and that doesn't make any difference. Also, checking in PhpMyAdmin, it doesn't seem as though the temporary table's being created. I'm obviously doing something wrong here or missing something, but I've no idea what.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
休息了一段时间后,我又回来了,正如你们所说,我实际上根本不需要临时桌子。
为了完整起见,并且以防其他人遇到同样的问题,这是最终的解决方案。
我最终发现,使用 SELECT 查询上的 when 子句,脚本可以正常工作,但我仍然没有获取任何数据(只是列名)。我终于弄清楚我没有获取任何数据的原因是因为虽然
'$session->username'
在我的 PHP 页面中工作以访问当前用户的名称,但脚本是仅链接到该页面,无法访问该会话信息。最后我发现我需要添加额外的变量
$username
并从 URL 上的查询字符串中获取该变量的值(不太确定我如何假设会话信息将到达脚本- 头没有转动!)。这是因为脚本无法访问'$session->username'
导致脚本无法正常工作。而不是使用以下方式链接到脚本:
我使用了这个(在页面上声明变量之后):
and:
然后我所要做的就是将 $username 变量添加到脚本顶部并使用该变量修改 SELECT 查询。
至少现在一切正常了! (我确实尝试了其他讨论中的一些建议,但无法使任何建议发挥作用 - 要么我只得到标题行,要么得到大量错误)。
Well after a bit of a break from this I've come back to it, and as you guys said, I didn't actually need a temporary table at all.
For the sake of completeness, and incase anyone else encounters the same problem, this was the eventual solution to it.
With the when clause on the SELECT query the script works fine, I eventually discovered, but I still wasn't getting any data through (just the column names). I finally figured out the reason I wasn't getting any data was because although
'$session->username'
works within my PHP pages to access the name of the current user, the script, which is only linked to the page, has no way to access that session info.Finally I worked out I needed to add in the extra variable
$username
and get the value for that from a query string on the URL (not quite sure how I was presuming the session info would get to the script - head wasn't in gear!). It was because the script couldn't access'$session->username'
that the script wasn't working.Rather than linking to the script with:
I used this instead (after declaring the variable on the page):
and:
Then all I had to do was add the $username variable into the top of the script and amend the SELECT query with the variable.
At least it all works now! (I did try some of the suggestions on the other discussion, but couldn't get any to work - either I got only the header rows or a load of errors).
如果列类型很简单,我有一个穷人的方法来制作 CSV 文件。这可以通过 CSV 存储引擎。
完成此步骤后,文件 /var/lib/mysql/mydb/books_csv.CSV 存在。
您可以按照自己的意愿打开文件。顺便说一句,所有字段都用双引号括起来。
尝试一下!
I have a poor man's approach to making a CSV file provided the column types are simple. It could be done by means of the CSV Storage Engine.
When this step is done, the file /var/lib/mysql/mydb/books_csv.CSV exists.
You can open file how you wish. BTW all fields are enclosed with double quotes.
Give it a Try !!!