简体   繁体   English

如何使用php从mysql导出数据

[英]how to export data from mysql using php

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]\n";
}
?>

which PHP version used? 使用哪个PHP版本?

The mysql extension is deprecated in php 5 later 稍后在php 5中弃用mysql扩展

PHP 5 and later can work with a MySQL database using: PHP 5和更高版本可以通过以下方式与MySQL数据库配合使用:

MySQLi extension (the "i" stands for improved) MySQLi扩展(“ i”代表改进)

PDO (PHP Data Objects) PDO(PHP数据对象)

Earlier versions of PHP used the MySQL extension. PHP的早期版本使用MySQL扩展。 However, this extension was deprecated in 2012. 但是,此扩展程序已于2012年弃用。

if you used php new version and mysql 如果您使用php新版本和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'];
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM