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?

Recommended Answers

All 2 Replies

Member Avatar for diafol

Why are you using MYSQLI constants with deprecated mysql functions?

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.