I am trying to export data from MySQL to CSV using PHP from a website. When a user clicks generate the report it will automatically create and this will be downloaded as a file on their computer. The code below I have been following an online tutorial but I have run into some issues. Currently, it will download but will only show one row with one date value from the MySQL data.
I was wondering what I need to do to show all the data in the csv file and how do I ensure that the names of the Rows are printed as well.
#header("Content-Disposition: attachment; filename=record.csv");
$select = "SELECT * FROM DBtable WHERE user_id=$id";
$result2 = $conn->query($select);
while ($row = $result2->fetch_assoc()) {
$data = $row['pain']."\n";
$data = $row['sleep']."\n";
$data = $row['mood']."\n";
$data = $row['heartrate']."\n";
$data = $row['time_of_entry']."\n";
}
echo $data;
exit();
Instead of setting the $row values to $data, you should echo instead
#header("Content-Disposition: attachment; filename=record.csv");
$select = "SELECT * FROM DBtable WHERE user_id=$id";
$result2=$conn->query($select);
while($row=$result2->fetch_assoc()){
echo $row['pain']."\n";
echo $row['sleep']."\n";
echo $row['mood']."\n";
echo $row['heartrate']."\n";
echo $row['time_of_entry']."\n";
}
exit();
Your code just keeps setting $data to a rows value, without actually doing anything with it. Each line overwrites the previous, so when you do echo $data, you are echoing the last value it was set to which in your case was the last loops "time of entry" value.
As for adding "names of the Rows", currently the code puts in a value then a new line. You probably want to replace "\n" with ",", so one loops data is one one line, then before the closing while loop, echo a "\n" to insert a new line character. You can then put the titles in the same way, using an echo, and comma seperated titles, followed by a new line character.
For example
echo $row['pain'].",";
echo $row['sleep'].",";
echo $row['mood'].",";
echo $row['heartrate'].",";
echo $row['time_of_entry'].",";
echo "\n";
Related
I am trying to download table data into a CSV format. The data in one of the fields contains ",".
Eg: Doe, John
When I download the csv file, the data after comma is shifted to next column. But I want the entire data i.e including comma in same column.
The Code I used as follows:
<?php
include('dbconfig.php');
//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=download.csv');
//select table to export the data
$sql ="SELECT * FROM tablename";
$select_table=mysqli_query($db, $sql);
$rows = mysqli_fetch_assoc($select_table);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysqli_fetch_assoc($select_table);
}
// get total number of fields present in the database
function getcsv($no_of_field_names)
{
$separate = '';
// do the action for all field names as field name
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('<em>', '', $field_name) . '';
}
echo $separate . $field_name;
//sepearte with the comma
$separate = ',';
}
//make new row and line
echo "\r\n";
}
?>
Can someone help me get through this issue.
Thanks
Make sure you escape the ,. Typically values that contain sensitive characters (such as , and \n) are surrounded in ".
So your output can be:
"Doe, John",52,New York
You can either write your own escape function or use PHPs fputcsv. It writes to a file handler that's a bit inconvenient but you can make it stdout.
$handle = fopen("php://stdout");
fputcsv($handle, array("Doe, John", 52, "New York"));
I'm trying to pass a value for a query that takes in a variable from an earlier Sql query and then compares the result against a field from another table. But I can't seem to figure out my syntax.
$topName = $row_rsAdminDetails['fullName'] ;
$TESTqueryTwo =
"SELECT * FROM participants, admin WHERE admin.over_id = participants.fk_over_id AND participants.dr_over_names LIKE '%$topName%'";
$TESTresult2 = mysql_query($TESTqueryTwo) or die(mysql_error());
the php output I'm looking to do:
<?php
// Print out the contents of each row
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
echo $row_TESTresultTwo['userName']. " - ". $row_TESTresultTwo['Participant_Name'];
echo "<br />";
}
?>
Problem could be on this line:
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
should be
while($row_TESTresultTwo = mysql_fetch_array($TESTresult2)){
// as you have no $TESTresultTwo variable...
}
And also try with the query ... with LIKE '%".$topName."%'"
I started using PHP with Oracle using ODBC commands. I used odbc_exec to get to query the database, which seems to work.
I am trying to print the dataset to a text file. I am able to write to the text file, but for some reason, I am only able to get back 1 record/row from the table.
One query in particular returns over 100 records. I would like to be able to print all 100 records in the text file.
I have researched all over the web, and I have come close to getting this work. In fact, I can print all the records to the web page. I just can't get all of the records into the text file.
Please see my code below and advise what I am missing.
<?php
$voyage = $_POST['voyage'];
$query = "SELECT * FROM voyageTable WHERE voyage = '".$voyage."'";
$result = odbc_exec($connect, $query);
while($row = odbc_fetch_array($result)) // have tried odbc_fetch_row already
{
$fullName = odbc_result($result, 1);
}
$dateFile = "CMDU-".$voyage."-".date('dmY').".txt";
$dataString = $fullName . "\n";
$fWrite = fopen($dateFile, "a");
$wrote = fwrite($fWrite, $dataString);
fclose($fWrite);
?>
I know I am close to getting this.
I have altered the while loop numerous times. I tried to do this as well:
<?php
while(odbc_fetch_array($result))
// ...
?>
Please help.
That was unsuccessful as well.
Instead of
$fullName = odbc_result($result, 1);
You need to either echo out like this:
echo odbc_result($result, 1);
Or store the result in an array like this:
$fullName[] = odbc_result($result, 1);
Just storing the value of each row in $fullname as a variable will overwrite the value and give you the last value from the last row in the result set.
Expanding on ಠ_ಠ's comment.
I'm trying to create an online database of the music I locally have on my computer. I already have a table of every song in my library and would like to create a different table with just the song ID's (auto-incremented when I added the songs to my main table) that act as one of my playlists.
From what I can tell, the only 100% certifiable method for matching the songs is by the location on my disk ( C:\Users\username\Music\iTunes\iTunes Media\Music\Jonathan Coulton and GLaDOS\Portal\128 128 Still Alive Duet.mp3 ) as an example. In my PHP code I get the song location into a variable and if I print it relative to the equivalent song location in my MYSql table, they match up exactly but when I try to run a select statement using that, it gives me an error. From what I can tell this is being caused by the backslashes in the location info.
This is the select statement I'm using,
SELECT id FROM itunes WHERE Location=$locationval
where $locationval is the current song's location, id is the autoincremented id in my main table, and itunes is my main table.
Is there any way around this? And as I am a beginner, is the backslashes really the issue?
For reference here is the full code for importing the playlist, its using the DB plugin for PEAR (a PHP extension).
<?php
// define table name
define('TABLE_NAME', 'playlist');
// create database connection
require_once('DB.php');
$dsn = 'mysql://username:password#localhost/itunes';
$DB =& DB::connect($dsn);
if (DB::isError($DB)) {
die($DB->getMessage());
}
$DB->setFetchMode(DB_FETCHMODE_ASSOC);
// load text file
$file = file_get_contents('Portal.txt');
// explode on new line
$file = explode("\r", $file);
set_time_limit(0);
// loop through each line in the file
foreach ($file as $key => $value) {
// explode on tab to get column list
$exploded = explode("\t", $value);
// check for first row, which contains column headers
if ($key == 0) {
}
else{
if(count($exploded)>3)
{
$locationval=$exploded[26];
echo $exploded[26];
echo "<br />";
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
//$result = mysql_query("SELECT * FROM itunes WHERE id=8292");
set_time_limit(0);
$row = mysql_fetch_row($result);
//test statements to see if the query worked
echo "Test: ";
echo $row['id'];
echo $row['Location'];
echo "<br />";
}
}
}
?>
Which was modified from the code here: http://ericlondon.com/posts/208-exporting-itunes-data-into-mysql-and-creating-sql-to-show-top-rated-albums
If any more info is needed, please let me know.
You need to escape the backslashes when using it in mysql as a string literal, so just replace your following line:
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
for this one:
$result = mysql_query("SELECT id FROM itunes WHERE Location='". str_replace('\\','\\\\',$locationval) . "'");
that should do what you want.
I've started making a Video script that loads the videos using MySql and I am using Mysqli.
However, There's 2 Rows that it should post, but it only post the second none, not the first one.
It loads the results using "Brand" so if there's 2 rows named "Test", it only loads the second one, but not the first one.
So, what is causing this? I've tried with 3 rows, and it did not include the first row.
Code
<?php
{ /* Global Data */
ini_set('display_errors', 0);
ini_set('error_reporting', -0);
$GetPath = $_GET['b'];
$SqlUser = "root";
$SqlPass = "**Private**";
$SqlHost = "localhost";
$SqlData = "heisteknikk";
}
{ /* Mysql Connect */
$Sql = new mysqli($SqlHost, $SqlUser, $SqlPass, $SqlData);
if ($Sql->connect_error) { die("Sorry, Could not connect (".$Sql->connect_errno.") ".$Sql->connect_error);}
}
{ /* Test */
$Brand = $Sql->real_escape_string($GetPath);
$SqlData = "SELECT * FROM videos WHERE Brand = '".$Brand."'";
$SqlQuery = $Sql->query($SqlData);
if (!$SqlQuery) {
echo $Sql->error;
}
if ($SqlQuery->num_rows == 0) {
die("Nothing was found");
}
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
echo "
<tr><td>".$Heis['Brand']."</td><td>".$Heis['Name']."</td><td>".$Heis['Location']."
";
}
echo "</table>";
$Sql->close();
}
?>
This line causes the bug:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
With this line you effectively throw out the first row of the result set, as you don't process $Data at all in the code below. Just remove it, and your script should work fine (I assume that closing </td></tr> sequence was lost when pasting the code, am I right?)
Comment out (or better yet, remove) this line:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
It is grabbing the first row...then you aren't doing anything with $Data and then grabbing the second (and consecutive rows) for display in your while loop. Commenting out that line above will make your loop grab and display them starting at the first one.
In your code
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
you're fetching a row (with fetch_array), throwing it away and then fetching another row (with fetch_assoc). That's probably why you're only seeing one row instead of two