douji1877 2015-07-23 10:02
浏览 32

如何使用php从mysql导出数据

I wanted to fetch some data from database and those data will be downloadable in text format.

For that I am using

<?php
$filename="abc.txt";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv");
echo "PHP is awesome";
?>

The above code is providing the option to download a file.

But when I am trying to add database connection in code that time I am not getting the download option. So I need help to solve the above problem.

My error Code:

<?php
$filename="abc.txt";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv");
$name="JONE":
$db_host =hostname;
$db_user =username;
$db_pass =password;
echo "$name";
mysql_connect( $db_host, $db_user, $db_pass );
$sql_query="select * from order";
echo "$sql_query";
$result = mysql_query($sql_query) or die('MySql Error' . mysql_error());
while ( $array = mysql_fetch_array($result) )
{
   echo "$array[0]
";
}
?>
  • 写回答

1条回答 默认 最新

  • duanguanye4124 2015-07-23 11:26
    关注

    which PHP version used?

    The mysql extension is deprecated in php 5 later

    PHP 5 and later can work with a MySQL database using:

    MySQLi extension (the "i" stands for improved)

    PDO (PHP Data Objects)

    Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

    if you used php new version and mysql

    you can try for your code

    <?php
    $filename="abc.txt";
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: text/csv");
    $name="JONE";
    $DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
    $DBUser   = 'root';
    $DBPass   = 'root';
    $DBName   = 'sms';
    echo "$name";
    $conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
    
    // check connection
    if ($conn->connect_error) {
      trigger_error('Database connection failed: '  . $conn->connect_error,
      E_USER_ERROR);
    } 
    
    $sql_query="select * from tmd_news";
    $rs=$conn->query($sql_query);
    
    if($rs === false) {
    trigger_error('Wrong SQL: ' . $sql_query . ' Error: ' . $conn->error, 
    E_USER_ERROR);
    } else {
     $arr = $rs->fetch_all(MYSQLI_ASSOC);
    }
    foreach($arr as $row) {
    echo $row['news_id'];
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害