Exporting Data from SQl to Excel Using PHP [duplicate] - php

This question already has answers here:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given [duplicate]
(2 answers)
Closed last year.
So the admin has the choice to choose what he want to export to excel by selecting checkboxes which i stored in col[]...
here's my code for exporting
session_start();
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DB = 'fyp_db';
$link = mysqli_connect($HOST, $USERNAME, $PASSWORD, $DB);
if (is_array($_POST['col'])) {
$sql = "SELECT ";
foreach ($_POST['col'] AS $value) {
$sql .= "{$value}, ";
}
$sql = substr($sql, 0, -2);
$sql .= " FROM account, coursedetail, coursecategory";
/*echo "sql= " . $sql . "<br /><br />\n";*/
} else {
echo "No column was selected<br /><br />\n";
}
function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\r?\n/", "\\n", $str); if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; }
$filename = "website_data.xls";
header("Content-Type: text/plain");
$flag = false;
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
I got the error of..
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in C:\xampp\htdocs\project\export_successful.php on line 28
why? :(

You're mixing up mysqli and mysql calls. The two libraries are NOT compatible and handles/statements returned by one cannot be used in the other.
$result = mysqli_query($link, $sql) or die(mysqli_error($link));
^--- note the 'i'
while(false !== ($row = mysql_fetch_assoc($result))) {
^--- note the LACK of an 'i'

Related

Exporting to CSV from MySQL via PHP

I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.
The PHP file is returning a blank CSV file & I can't figure out why & I've been stuck on this for quite a while, so any help would be much apprwciated.
Code below:
<?
include('../../../inc/config.php');
$period = $_GET['pid'];
$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];
$query="SELECT
sid,
date,
stove_id,
name,
gender,
marital_status,
occupation_of_household,
cz_stove AS km_stove,
happy_with_cz_stove AS happy_with_km_stove,
cz_stove_in_use AS km_stove_in_use,
know_how_to_use,
FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
//header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
hey i have a code you can use it like this
<?PHP
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>
The issue is that you are not writing anything to the csv file before opening it.
Use this code
$fp = fopen($filename, 'w');
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
fputcsv($fp, $headers);
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Type: text/csv');
header( "Content-disposition: filename=".$filename);
readfile($filename);
Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks #Tintu C Raju for pointing me in the right direction

php data_seek in user function

I have connection with mysql & need to get query results many times.
I use:
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
Then query:
$query = "CALL raport6('2014-01-01', '2014-12-31', 300);";
$result = $mysqli->query($query);
I have function in separate file which gives me header names:
function headers($result) {
global $result;
$field_cnt = $result->field_count;
$string ="";
while ($finfo = $result->fetch_field()) {
$currentfield = $result->current_field;
$string .= "'" . $finfo->name . "'";
if ($currentfield == $field_cnt) {break;}
$string .= ",";
}
$result->data_seek(0);
return $string;
}
Then I call this function twice, and get only 1 (first) result:
echo "function 1:" . headers($result);
echo "function 2:" . headers($result);
I used $result->data_seek(0); to reset pointer... but it doesn't work in function. If I use function code in file twice - then it works.
Do you know why?
Cheers!
You could make that function a whole lot simpler
function headers($result) {
$string = '';
while ($finfo = $result->fetch_field()) {
$string .= sprintf("'%s',", $finfo->name);
}
// and here is the fix
$result->field_seek(0);
// to remove last comma if required
// return rtrim($string, ',');
return $string;
}

create excel file of database query result in php

I create excel file using php.It has contain Query Result data from database.Excel file generate and download very well but when i opened i found it gives some format error and some coding error also.
function generate_excel($conn) {
$filename = "website_data_" . date('Ymd') . ".xls";
function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-type: application/octet-stream;charset=utf-8");
$flag = false;
$qry = "SELECT ContactId,UniqueContactId FROM Contacts ORDER BY ContactId ";
$stmt = sqlsrv_query($conn, $qry);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
while (false !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
}
sqlsrv_fetch_array() can return either NULL or FALSE. You can make your while statement as follows:
while (NULL !== ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
if(!$row)
break ;
//...
}
Here's PHP function reference: http://php.net/manual/en/function.sqlsrv-fetch-array.php

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

Convert strings into asterisks

im working on a php-based system. one of its features is allows user to download an excel file containing all the information in one of my table in my database. my problem is, one data of that information is classified to other users. thus, i want to convert the output of that data into a string of asterisk.
<?PHP
//MySQL Database Connect
include 'datalogin.php';
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
# filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
//$result = pg_query("SELECT * FROM data_mapping ORDER BY CE_Hostname") or die('Query failed!');
/*$query = "SELECT * FROM data_mapping";
while(false !== ($row = pg_fetch_assoc($result))) {
//while(false !== ($row = pg_fetch_assoc($result))) {
//$result=mysql_query($query);
$row=mysql_fetch_array($result);
$row=mysql_fetch_assoc ($result);
//$row=$row['Cust_Segment'];
// foreach($data as $row)
# display field/column names as first row
if(!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t",($row)) . "\r\n";
}
*/
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type, com_string FROM data_mapping';
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not query the database<br>";
echo 'MySQL Error: ' . mysql_error();
exit;
}
echo "Hostname\t Group/System\t Site Name\t IP ADDR\t BKP IP ADDR\t System Name\t Device Type\t Comm_String\r\n";
while ($row = mysql_fetch_assoc($result)) {
echo implode("\t",($row)) . "\r\n";
}
mysql_free_result($result);
//exit;
?>
i want to convert only the comm_string result. thanks.
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type, com_string FROM data_mapping';
Can simply be updated to not included the classified field
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type FROM data_mapping';
Or if you still want to show some value there without any change in your PHP code then you could do
$sql = 'SELECT CE_Hostname, Cust_Segment, Cust_Site_Name, CE_WAN_IP_Addr, CE_Bkp_IP_Addr, Cust_Name, Svc_Type, 'SECRET' FROM data_mapping';
This will then show SECRET instead of that code
Try this:
while ($row = mysql_fetch_assoc($result))
{
$row['Comm_String'] = preg_replace( '/./', '*', $row['Comm_String'] );
echo implode("\t",($row)) . "\r\n";
}

Categories