dongre6073 2015-05-24 10:12
浏览 231

PHP Sql语句从MySQL导出表数据

In my site when Admin is logged in I want him to be able to export a table in phpmyAdmin to a Excel sheet. I was able to do it manually by export button in phpMyAdmin but I want to be able to do this using a SQL statement. This is the first time I am trying it and after looking at exporting-table-structure-to-excel-files-with-phpmyadmin and phpmyadmin-exporting-to-csv-for-excel

I wrote the following code.

if($level==1){
    echo "<br>";
    $q9=" SELECT * INTO OUTFILE 'C:\xampp\htdocs\excelsheet1.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY ''
LINES  TERMINATED BY '
'
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_SCHEMA = DATABASE('db1') AND TABLE_NAME ='tb1'";
$s9=mysql_query($q9,$connect) or die("couldn't export values");
    }  

I have created a blank .csv fie in C:\xampp\htdocs named as excelsheet1.csv. But when I run this code it gives the error couldn't export values and there's a blank excel sheet. In the PHP statement how can I write OPTIONALLY ENCLOSED BY '"' inside SELECT because if I use " inside SELECT I get a syntax error. What can I do to export values in tb1 to excelsheet1.csv

  • 写回答

1条回答 默认 最新

  • dongqin5604 2015-05-27 03:41
    关注

    The code you're writing is PHP only, not for phpMyAdmin (which is an administrative GUI interface for managing a MySQL database), so you might be searching based on some misleading keywords.

    I suggest you first try running that SQL statement from the command line client -- does it work as expected there? If you run the query without the CSV export part does it show the output you expect?

    Your query looks odd to me, I'm not sure about the DATABASE('db1') part -- you're calling the MySQL function DATABASE but I don't think it takes any arguments, so the 'db1' part is either ignored or throwing a warning or error. I don't see that you set a default database, so the function is probably returning NULL anyway.

    In the TABLE_NAME ='tb1' part, you should use backticks like ` instead of single quotes like '

    Back to the PHP side of things, in your error detection code, you could print the error message from MySQL to better see what the problem is.

    Finally, unrelated to your problems, the mysql functions have been depreciated and it's recommended that you switch to pdo or mysqli instead.

    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误