I'm new to PHP. I'm using the following code to generate an excel sheet from Mysql database using PHP.
<?php
include("../Connection/Connection.php");
$db_con=new Connection();
$db_con->get_connection(); //Opens a database connection. This function is contained in the Connection.php which is included above.
$result = mysql_query("SELECT * FROM country");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_array($result))
{
fputcsv($fp, array_values($row));
}
die;
}
?>
The above code is working and it generates the specified file export.csv but the problem is that it generates each column from MySql in this file twice. In other words, each column is duplicated twice (headers displayed are not duplicated though). What is wrong with this code? What changes should be made so that it displays each column exactly once?
Use mysql_fetch_row instead.
mysql_fetch_array fetches an array with BOTH string indexes and numeric indexes, so each value is fetched twice. Your code would work with either mysql_fetch_assoc or mysql_fetch_row.
Related
I have a php script that exports a mysql database table to a csv file. For one of the fields of data, a user included an octothorp # in their text. For example, My Idea #1.
When my code gets to this piece of data, it stops at the # symbol. I'm guessing it hits the # and believes everything else that follows is a comment.
As a temporary solution, I am stripping out this symbol when adding the data to the database, but this is not ideal. Given the script below, how might I escape this symbol to prevent this from happening?
$query = "SELECT * FROM my_table";
$result = #mysqli_query($dbc, $query);
if (!$result) {
die('Couldn\'t fetch records');
}
$num_fields = mysqli_num_fields($result);
$headers = [];
for ($i = 0; $i < $num_fields; $i++) {
$field = mysqli_fetch_field_direct($result, $i);
// var_dump($field);
$headers[] = $field->name;
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
I am trying to export a table from a mysql db to csv.I am able to do this successfully,however, it doesnt export the column names,is there any way i achieve this?Some pointers would be great.Please check out my data_export.php file below:
<?php
include 'class.user.php';
$conn=mysqli_connect("localhost","root","PASSWORD","reflective");
#declare the school variable for use in the select* query
$school = $_POST['school'];
#query the students table for data to export
$select="SELECT * FROM students WHERE school_id ='$school'";
$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);
$headers ="";
while ($property = mysqli_fetch_field($result)) {
$headers.= $property->name.",";
}
$headers.="\n";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="students_data.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
I would suggest you use the array_keys() method in PHP. It will extract all the keys from the array you fetch from the database. You just need to pass the first array as argument in the method like this,
array_keys($data[0]);
i am trying to fetch all data from a table and save into a csv file.
i did not get any error but it is not creating the csv file with the result as well.
but when i see the output i see that the results is there but why the csv file is not creating for the result!!
PHP code --
$result = mysql_query('SELECT * FROM `info_contact`');
if (!$result){
die('Couldn\'t fetch records');
}
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result, $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="myCsvFile.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result)) {
fputcsv($fp, array_values($row));
}
die;
}
Output ---
id,name,email,message,content,contactTime
34,chris,christoferhansen#gmail.com,"Hi Chris","C:fakepathCoding style.pdf","2015-11-29 19:49:02"
35,Hansen,hansen#yahoo.com,ad,,"2015-11-29 19:52:20"
Where is my mistake for not being able to create a cvs file !
Can anyone help me with this please
You script create csv for download. If you have write it to file on server than replace $fp = fopen('php://output', 'w'); with $fp = fopen('path/to/file.csv', 'w'); and remove all header calls
I need Name,Given phonenumber mobile notes location to all be in separate columns on my csv export using the php script below. The current code exports all of the selected data in one column for each record. Thank you!
$result = mysql_query('SELECT who as "Name,Given" , phonenumber as "mobile", notes, location FROM `phpbb_phonelist` WHERE `activenumber` = 1');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="phonelist.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
Use this code
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
I want to generate excelsheet using php so which method or code is preferable to use to generate dynamic excelsheet? Please check a screenshot image for more idea what I am facing issue.!
screenshot of required excel sheet format
Please, anyone can help me to sort out these issue? Thanks in advance.
I am using below code example.
$result = mysql_query("SELECT * FROM ".$pre."customers");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export1.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
But I don't that I can lock any cell into this excel sheet. So which php method or class are suitable to generate excelsheet for my purpose to use?
public function get_excel($err = array())
{
// Clear any previous output
ob_end_clean();
// I assume you already have your $result
$search = ($this->uri->segment(2))?$this->uri->segment(2):'key';
$result=mysql_query("select * from job");
$num_fields = mysql_num_fields($result);
// Fetch MySQL result headers
$headers = array();
//$headers[] = "serial no";
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = strtoupper(mysql_field_name($result , $i));
}
// Filename with current date
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
// Open php output stream and write headers
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
// Write mysql headers to csv
fputcsv($fp, $headers);
//$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// $row_tally = $row_tally + 1;
//echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
}
It seems like you want more out of CSV than possible. Are you aware of the import functions in excel? You can easily set up the document to recieve only the dynamic content as CSV (lower part) from your own php-service etc...
My version of Excel is danish but its under det data-tab and something like "from internet" :)