Export more than one DB Table as SQL Data - php

I'm looking to export 11 Database tables' data as XML. I've easily managed to export one table, without issue. But I am looking to export more than one really.
I'm sure theres a way and obviously output the data as seperate table entitys. Any help is much appreciated on this one, As I'm finding it a little tricky.
My code is as follows
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "";
$database = "db_etch";
$table = "keywords";
$SQL_query = "SELECT * FROM $table";
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
// produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
// root node
$XML .= "<result>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t<$table>\n";
$i = 0;
// cells
foreach ($row as $cell) {
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = mysql_field_name($result,$i);
$XML .= "\t\t<" . $col_name . ">" . $cell . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t</$table>\n";
}
$XML .= "</result>\n";
// output the whole XML string
echo $XML;
// Write $sql to file
$File = "keywords.xml";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = $XML;
fwrite($fh, $stringData);
fclose($fh);
?>

I changed some of your code, assuming some little extra what you wanted:
Changed str_replace() to htmlspecialchars()
Moved xml start to the beginning.
Added a new root node.
That's about it. If you want to output all tables from a certain db, you should use "show tables;" -query to find out the tables that the db consist of.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "";
$database = "db_etch";
$table = "keywords";
$tables_to_output_array = array('keywords', 'othertable1', 'othertable2');
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
// produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
// root node
$XML .= "<tables>\n";
while (list(, $table) = each($tables_to_output_array)) {
$SQL_query = "SELECT * FROM $table";
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
// tables
$XML .= "\t<$table>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t\t<row>\n";
$i = 0;
// cells
foreach ($row as $cell) {
$col_name = mysql_field_name($result,$i);
$XML .= "\t\t\t<" . $col_name . ">" . htmlspecialchars($cell) . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t\t</row>\n";
}
$XML .= "\t</$table>\n";
}
$XML .= "</tables>\n";
// output the whole XML string
echo $XML;
// Write $sql to file
$File = "keywords.xml";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = $XML;
fwrite($fh, $stringData);
fclose($fh);
?>

Related

excel automatically open file after downloading in php

below is my codes for my excel. its functioning except for one thing. i don't see if my file is already save to excel.. can you help me how to automatically open my file after i download it.. i think something is missing or wrong in my codes.. so please. help . thanks.
{
$conn = mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("copylandia",$conn);
//$fp = fopen($filename,"w+");
$filename = 'attachment'. date('Y-m-d') .'.csv';
$fp = fopen($filename,"w+");
$sql = mysql_query("select * from user") or die (mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w+");
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$name);
$comma = ",";
}
$seperator .= "\n";
//echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
else
{
echo 'No records in the database!';
}
}
You can't force the browser/computer to open a file after download. The user must make that decision.
Although, since you are trying to make a CSV file, I will at least make a suggestion to help you out instead of crushing your dreams by telling you you can't do this:
Try fputcsv() instead of trying to make the string yourself:
I'm really cool! Click me!

How to create a new file in every iteration of a PHP program?

I am creating a file using PHP but I am unable to create a new file in every execution of the application. I am generating an XML file using a database. I want a new file in every execution of my code, how can I do that?
This is my code:
<?php
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "root";
$config['mysql_pass'] = "root";
$config['db_name'] = "dcu";
$config['table_name'] = "readingsThreePhase";
//$config['table_name1'] = "miosD1";
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
#mysql_select_db($config['db_name']) or die( "Unable to select database");
function writeMsg()
{
//echo "Hello world!";
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."D1";
$xml .= "<$root_element>";
$sql = "SELECT * FROM dcu.readingsThreePhase where meterId=3 order by recordTime DESC limit 1";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
//$xml .= "<".$config['table_name'].">\n";
$xml .= "<".$config['miosD1'].">\n";
foreach($result_array as $key => $value)
{
if($value==NULL)
{
continue;
}
$xml .= "<$key>";
$xml .= "$value";
$xml .= "</$key>\n";
}
$xml.="</".$config['miosD1'].">";
}
}
$xml .= "</$root_element>";
header ("Content-Type:text/xml");
echo $xml;
$file=fopen("xmlfilefirst.xml","a");
fwrite($file,$xml);
fclose($file);
}
writeMsg();
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."s";
$xml .= "<$root_element>";
$sql = "SELECT * FROM dcu.readingsThreePhase where meterId=3 order by recordTime DESC limit 1";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<".$config['table_name'].">\n";
foreach($result_array as $key => $value)
{
if($value==NULL)
{
continue;
}
$xml .= "<$key>";
$xml .= "$value";
$xml .= "</$key>\n";
}
$xml.="</".$config['table_name'].">";
}
}
$xml .= "</$root_element>";
header ("Content-Type:text/xml");
echo $xml;
$file=fopen("xmlfilefirst.xml","a");
fwrite($file,$xml);
fclose($file);
?>
use file_put_contents
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
To create a new file every time, you need a way to generate a unique filename. You can either create this name with some sort of gibberish, such as:
do {
$filename = 'my_file_' . substr(md5(time( ), 0, 8 ) . '.xml';
} while( file_exists( $filename ) );
Or, you can attempt with some sort of numeric naming convention ('myfile1.xml', 'myfile2.xml', 'myfile3.xml' etc). This would mean getting a listing of the current directory. If no files are present, start with 1. Otherwise, start with the count of files + 1 and name your file with that.
See also the documentation for fopen. Most of the modes will attempt to create a file if the specified filename does not exist, so just coming up with a unique filename is the trick.

convert from mysql php script to pdo

I am actually new to PDO
Here I am trying to fetch data from mysql and show in xml.
I have done it using mysql, but I could not be able to done it using PDO.
Here is my PHP code
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "root";
$database = "my_db";
// replace by a real *.xsl file, e.g.
// $xslt_file = "exam.xsl";
$xslt_file = FALSE;
// If true, will output XML without XSLT
$raw = TRUE;
$SQL_query = "SELECT * FROM `battery` order by waste asc";
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
$left = "<";
$right = ">";
if ($xslt_file or $raw) {
// we produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
if (!$raw) $XML .= "<?xml-stylesheet href=\"$xslt_file\" type=\"text/xsl\" ?>";
}
else {
// we produce HTML. All XML tags are replaced by printable entities
$XML = "Don't forget to create an XSLT file .... <p>";
$XML .= "<pre>\n";
$left = "<";
$right = ">";
}
// root node
$XML .= $left . "result" . $right . "\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t" . $left. "row" . $right . "\n"; // creates either "<row>" or "<row>"
$i = 0;
// cells
foreach ($row as $cell) {
// Escaping illegal characters
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = mysql_field_name($result,$i);
// creates the "<tag>contents</tag>" representing the column, either as XML or for display in HTML
$XML .= "\t\t" . $left . $col_name . $right . $cell . $left . "/" . $col_name . $right ."\n";
$i++;
}
$XML .= "\t" . $left. "/row" . $right . "\n";
}
$XML .= $left . "/result" . $right . "\n";
echo $XML;
if (!$xslt_file && !$raw) echo "</pre>";
?>
I am trying a lot, but i could not be able to done it using PDO
Please i need some help.
Any Help will be appreciated.
My PDO code that i tried is
<?php
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "my_db";
$dbuser = "root";
$dbpass = "root";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$xslt_file = FALSE;
$raw = TRUE;
$SQL_query = "SELECT * FROM `battery` order by waste asc";
$result = $conn->query($SQL_query);
$left = "<";
$right = ">";
if ($xslt_file or $raw) {
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
if (!$raw) $XML .= "<?xml-stylesheet href=\"$xslt_file\" type=\"text/xsl\" ?>";
}
else {
$XML = "Don't forget to create an XSLT file .... <p>";
$XML .= "<pre>\n";
$left = "<";
$right = ">";
}
$XML .= $left . "result" . $right . "\n";
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$XML .= "\t" . $left. "row" . $right . "\n"; // creates either "<row>" or "<row>"
$i = 0;
// cells
foreach ($row as $cell) {
// Escaping illegal characters
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = $result->fetchAll(PDO::FETCH_COLUMN);
// creates the "<tag>contents</tag>" representing the column, either as XML or for display in HTML
$XML .= "\t\t" . $left . $col_name . $right . $cell . $left . "/" . $col_name . $right ."\n";
$i++;
}
$XML .= "\t" . $left. "/row" . $right . "\n";
}
$XML .= $left . "/result" . $right . "\n";
echo $XML;
if (!$xslt_file && !$raw) echo "</pre>";
?>
But it shows nothing
The correct way to fetch column names is
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
however as you are fetching an assoc you could just change your foreach loop to this:
foreach ($row as $col_name => $cell) {
There may be other issues, have you tried using print_r on the result of each PDO function call to check at what point it is failing?
you connect to the database like this :
$dbhost = "localhost";
$dbname = "testcreate";
$dbuser = "root";
$dbpass = "mysql";
try {
$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname.';charset=utf-8', ''.$dbuser.'', ''.$dbpass.'');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Error : <br>' . $e->getMessage();
}
PS: You dont need the try and the catch, but we used to get the error and handle it in a nice way as we want to
and next we query like this :
$db->query(SELECT * FROM node WHERE node_name='$nodename'");
and we fetch it like this :
$query = $db->query(SELECT * FROM node WHERE node_name='$nodename'");
$row = $query->fetch(PDO::FETCH_OBJ);
and now you use $row->name for example
here is more about PDO::FETCH
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were
bound with the PDOStatement::bindColumn() method
PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the
class. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g.
PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class
is determined from a value of the first column.
PDO::FETCH_INTO: updates an existing instance of the requested class, mapping the columns of the result set to named properties in
the class
PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed
PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0
PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set

Remove occurances of ",,," from MySQL Database Output PHP

I am outputting the contents of my MySQL Database into a text file using the below code:
<?php
$host = 'localhost';
$user = 'myusername';
$pass = 'mypassword';
$db = 'mydbname';
$table = 'mytablename';
$file = 'outputfilename';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
//$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
//echo $csv_output;
$myFile = "output.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $csv_output;
fwrite($fh, $stringData);
fclose($fh);
exit;
?>
However I would like to know how I could replace the occurances of the string ",,," with this: "," before it goes into the text file.
No need for preg_replace().
A simple str_replace will suffice.
$stringData = str_replace(',,,', ',', $csv_output);
problem is in:
$values = mysql_query("SELECT * FROM ".$table."");
if you got ,,,, it means that some columns has no value. Detect those columns, do not include them in SELECT statement.
if you will automatically (preg_replace, str_replace) change multiple commas to one comma, you are on good way to corrupt CSV file.
Use preg_replace(). Something like this (untested):
$pattern = '/\,\,\,/';
$replacement = ',';
echo preg_replace($pattern, $replacement, $stringData);
add this code:
while ($csv_output=str_replace(',,', ',', $csv_output)) echo '.';
OR change the for code:
for ( $j=0; $j<$i; $j++) {
$csv_output .= (isset($rowr[$j])) ? $rowr[$j]."," : '';
}
str_replace()
$stringData = str_replace(',,,', ',', $stringData);
http://php.net/str-replace

PHP export to Excel file gives me source code in columns

I feel like I'm making a simple mistake but I can't seem to figure out what.
I have some code for exporting a mySQL table to an Excel file.
However, when I do the export, the entire HTML source code gets exported along with my data. I open the file in Excel and my table data in there but it's also got all the HTML inside.
What could be causing all the source code to be exported along with the data?
I should mention that I'm using this code as part of a Wordpress plugin I'm writing. When I test the export outside wordpress, it works fine. But when I try to export from a Wordpress admin page, I get all the extra HTML source code.
Try this code.
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$res = mysql_query("SELECT * FROM $table");
// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
// remove the result pointer back to the start
mysql_data_seek($res, 0);
// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
fclose($fp);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
Thanks,
Kanji

Categories