Page 1 of 1

DB to excel code

Posted: Mon Feb 09, 2009 8:29 am
by oduth
Hi everyone,

I got a code importing the first column data of database to an csv file. But, i couldn't figure it out how can i do that for the other columns of database.

Any help would be greatly appreciated!

column names : hostname, ip_address, primary_admin, secondary_admin, join_date

Below gives me only the hostname column in csv file.

<?php

class DBToExcel
{
private $db_handle;
private $user_name;
private $password;
private $data_base;
private $host_name;
private $sql;
private $results;

function __construct($host="localhost",$user,$passwd)
{
$this->db_handle = mysql_connect($host,$user,$passwd);
}

function dbSelect($db)
{
$this->data_base = $db;
}

function executeSql($sql_stmt)
{
$this->sql = $sql_stmt;
$this->result = mysql_query($this->sql);
}
function returnResults()
{
return $this->result;
}
}

$user = "root";
$passwd = "";
$db = "inventory";
$sql = "select * from systems where status='active'";

$dbObject = new database($host="localhost",$user,$passwd);
$dbObject->dbSelect($db);
$dbObject->executeSql($sql);

$res = $dbObject->returnResults();

$file_name = "systems.csv";

$fpWrite = fopen("C:\\$file_name", "w");

$nameStr = "";

while($record = mysql_fetch_object($res))
{
$name = $record->hostname;

$nameArray = explode("\n",$name);

if(count($nameArray) > 1)
{
$nameTemp = "";
for($i=0;$i < count($nameArray); $i++)
{
$nameTemp = $nameTemp . $nameArray[$i];

if($i != (count($nameArray) - 1))
$nameTemp = $nameTemp . "&sbquo;";
}
$name = $nameTemp;
}

$nameStr = $nameStr.$name."\n";
}

fwrite($fpWrite,$nameStr);
?>

Re: DB to excel code

Posted: Mon Feb 09, 2009 12:47 pm
by andyhoneycutt
i think you need to move your fwrite into the while loop.

-Andy

EDIT: or concatenate onto $nameStr.