exporting a .csv file from download button - php

EDIT: I changed "echo($row)" to "print_r($row)" and now the csv that's being downloaded has each array in parenthesis with all the data mentioned, but how do I customize the way it all can be printed?
Right now, it's printing:
Array (
[id]=>1
[firstname]=>"Timmy"
)
Array (
....
(where each line is the next row in the excel spreadsheet)
How would I make this output so that each record has it's own row? for example the first column in excel would be id, then the second would be firstname, with each record it's own row?
I've got a link in my main.php:
<a class="btn" href="export.php">Export</a>
Then here's my export.php file:
<?php
//open database connection
try {
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8',
'DBUSER',
'DBPASS');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $ex) {
echo "did not connect...";
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');
$sql = "SELECT * FROM table_name;";
$sth = $db->prepare($sql);
$sth->execute();
$filename = date('d.m.Y').'.csv';
$data = fopen($filename, 'w');
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
fputcsv($data, $row);
print_r($row);
}
echo "\r\n";
fclose($data);
?>

In order to get an associative array to be placed properly into your file you'll need to parse the array and then put the line in the file:
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$csv = implode(',', $row) . "\n";
fwrite($data, $csv);
print_r($csv);
}

I assume your output should be a csv file with the date as a file name, am I correct?
Could you try this:
UPDATED CODE
<?php
//open database connection
try {
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8',
'DBUSER',
'DBPASS');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $ex) {
echo "did not connect...";
}
$sql = "SELECT * FROM table_name";
$sth = $db->prepare($sql);
$sth->execute();
$filename = date('d.m.Y').'.csv';
$data = fopen($filename, 'w');
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
fputcsv($data, $row);
}
fclose($data);
?>
The code will break because the "." is in the wrong place.
$filename = date('d.m.Y').'.csv'; is not the same as $filename = 'date('d.m.Y').'.csv';
#NoReceipt4Panda: I can not comment so Code is updated.
You should be using $sth = $db->prepare($sql); not $sth = $conn->prepare($sql);.
You don't have a variable with the name $conn.

Related

Insert Base64 Images to Array PHP PDO

I'm trying to insert Blob images retrieved from MySQL into an array using a while loop.
The database statement selected all images then i need to pass them all into an array.
So in theory, i should have an array of base64 encoded image corresponding to each record from my database.
Any help will be appreciated.
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
//$result = base64_encode(); ---- Something here im guessing
$data[] = $result;
}
print_r ($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I see big issue i your code..
You use the same variable, $result, for fetching mysql row result and image content.
Second, you miss to encoding to base64 the file content.
Here is my solution:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result['img']);
}
print_r ($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
Hope it will helps you.
So the answer to this question came from AbraCadaver.
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
Thanks guys for the help!

reading entries from database

is anyone able to find out what went wrong in this code below? It just shows a blank page. I'm new to PDO, always used mysqli but someone told me to try PDO since my page had problems showing arabic characters.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;'
$user = 'dbuser'; // don't hardcode this...store it elsewhere
$password = 'dbpass'; // this too...
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT :column FROM :table";
$opts = array(
':column' => 'Name',
':table' => 'Mothakirat'
);
$dbh->beginTransaction();
$statement = $dbh->prepare($sql);
if ($statement->execute($opts)) {
$resultArray = array(); // If so, then create a results array and a temporary one
$tempArray = array(); // to hold the data
while ($row = $result->fetch_assoc()) // Loop through each row in the result set
{
$tempArray = $row; // Add each row into our results array
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray); // Finally, encode the array to JSON and output the results
}
$dbh->commit();
</html>
This has no parse errors checked in my IDE. I use netbeans, its very good and available on several platforms.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;';
$user = 'dbuser'; // don't hardcode this...store it elsewhere
$password = 'dbpass'; // this too...
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT :column FROM :table";
$opts = array(
':column' => 'Name',
':table' => 'Mothakirat'
);
$dbh->beginTransaction();
$statement = $dbh->prepare($sql);
if ($statement->execute($opts)) {
$resultArray = array(); // If so, then create a results array and a temporary one
$tempArray = array(); // to hold the data
while ($row = $result->fetch_assoc()) // Loop through each row in the result set
{
$tempArray = $row; // Add each row into our results array
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray); // Finally, encode the array to JSON and output the results
}
$dbh->commit();
?>
</html>

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

PHP-PDO fetch data using loop structure

I am practicing using PDO fetch methods to retrieve data from the table. I would like to a counter in a while loop to retrieve data one row at a time. Please give me some advise how to accomplish this. Thanks!
Here are my 2 code samples using PDO::Query() and PDO::fetch() method.
code sample 1 using PDO::Query() Method
$sql = 'select first_name, last_name, pd, b_month, b_day, b_year from reg_data';
$birth_date = '';
try
{
foreach($con->query($sql) as $row)
{
print $row['first_name'] . " ";
print $row['last_name']. " ";
print $row['pd'] . " ";
$birth_date = $row['b_month'] . "-". $row['b_day'] . "-". $row['b_year'];
print "$birth_date";
}
}
catch(PDOException $e)
{
echo " There is a problem with you db connection";
echo $e->getMessage();
}
sample 2 using PDO::fetch() method
try {
$con = new PDO ($dns, $db_uid, $db_pd, $option);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select * from reg_data";
$stmt = $con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
//using cursor to interate through array
while($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
$data = $row[0].$row[1]. $row[2] .$row[3].$row[4].$row[5];
print $data;
}
$stmt = null; //close the handle
}
catch(PDOException $e)
{
echo " There is a problem with you db connection";
print $get->getMessage();
}
I think you need PDO::fetchAll.
A code example straight from the tag wiki:
//connect
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);
//retrieval
$stm = $pdo->prepare("select * from reg_data");
$stm->execute();
$data = $stm->fetchAll();
$cnt = count($data); //in case you need to count all rows
//output
?>
<table>
<? foreach ($data as $i => $row): ?>
<tr>
<td><?=$i+1?></td> <!-- in case you need a counter for each row -->
<td><?=htmlspecialchars($row['first_name'])?></td>
</tr>
<? endforeach ?>
</table>
You can use a variable and increment it in the loop
$counter++ ;

Unable to execute fetch(PDO::FETCH_ASSOC) and not updating csv file

// First, prepare the statement, using placeholders
$query = "SELECT * FROM tableName";
$stmt = $this->connection->prepare($query);
// Execute the statement
$stmt->execute();
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "Hi";
// Export every row to a file
fputcsv($data, $row);
}
Is this correct way to do and if yes than why do I get false value for var_dump and than it does not go into while loop and does not write into csv file.
Any suggestions ?
One thing that is missing is that you first need to open the csv file:
$fp = fopen('file.csv', 'w');
then you can put data into it:
fputcsv($fp, $data);
As for the var_dump printing out false, you would have to provide more information about what objects you are actually using I think. (ie: what is $this->connection ?)
I don't know if this will help, but try to do it without the $this->connection:
$config['database'] = 'sakila';
$config['host'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$d = new PDO('mysql:dbname='.$config['database'].';host='.$config['host'], $config['username'], $config['password']);
$query = "SELECT * FROM actor";
$stmt = $d->prepare($query);
// Execute the statement
$stmt->execute();
var_dump($stmt->fetch(PDO::FETCH_ASSOC));
$data = fopen('file.csv', 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "Hi";
// Export every row to a file
fputcsv($data, $row);
}

Categories