0

Hello,
I want to fetch database table in csv file format.
I tried but in my output file every fethced line is getting printed on new line.
code is as below

<?php
$host="a.b.c";
$uname="root";
$pass="test";
$database ="TEST"; 
$connection=mysql_connect($host,$uname,$pass); 
echo mysql_error();
// Fetch Record from Database
$output = "";
$table = "abc"; // Enter Your Table Name 
$result = mysql_query("select * from $table");

$row = mysql_fetch_array($result, MYSQLI_ASSOC);
$mytags= array();
$fp = fopen('/var/www/myFile.csv', 'w');

while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($row as $val) {
    $mytags= array(); // this is because it was giving warning of parameter should be an array
    array_push($mytags,$val);
    fputcsv($fp, $mytags);
    $mytags= array();
}
}

fclose($fp);

?>

what is problem in code?

2
Contributors
2
Replies
13
Views
2 Years
Discussion Span
Last Post by Priti_P
0

Hello,
Thanks for above mistake.
But I put wrong code here.
please cosnider below code which is not working as expenctations:

<?php
$host="a.b.c";
$uname="root";
$pass="test";
$database ="TEST"; 

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();
$result=mysql_select_db($database)
or die("database cannot be selected <br>");

// Fetch Record from Database
$output = "";
$table = "test"; 
$result = mysql_query("select * from $table");

if($result === FALSE) {
    die(mysql_error());
}

$mytags= array();
$fp = fopen('/var/www/myFile.csv', 'w');

while ($row = mysql_fetch_array($result)) {
foreach ($row as $val) {
    $mytags= array();
    array_push($mytags,$val);
    fputcsv($fp, $mytags);
    $mytags= array();
    }
}
fclose($fp);

?>

what is wrong in while loop which is not writting my csv file correct?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.