Generate CSV file using PHP Codeigniter Framework [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to generate a csv file, using data from a database. How does one do this in PHP CodeIgniter framework?

Take a look at this answer of mine and you will know exactly how you can do it.
Reports in Codeigniter
You need to use Codeigniter Database Utility Class
And need to return query instead of result_array or result

function query_to_csv( $query, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result = mysql_query($query);
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result, 0);
}
}
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
exit;
}

Related

php not backing up Mysql databases using exec() for mysqldump [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
I'm using php to automate a backup process of my databases, process runs with no error and create the .sql.gz files, but all of them are of a fixed size of 350 byte, useless. I'm using exec() function to read the return value and get the output from mysqldump.
return is always 0 and I cannot print the output to see if there is an error.
This is the code I'm using:
#Process begins
$conn = new mysqli("localhost", $user, $pwd);
$result = $conn->query("SHOW DATABASES");
if ($conn->affected_rows > 0){
$conn->close();
while( $db = mysqli_fetch_row($result)){
$return=null;
$output=null;
if (($db[0]!="information_schema") && ($db[0]!="mysql")) {
$filename = "$targetdir/$db[0]-$filetime.sql";
$cmd = "mysqldump -u $user -p$pwd $db | gzip > $filename.gz";
exec($cmd, $output, $return);
if ($return==0) {
file_put_contents($logfile, serialize($output), FILE_APPEND);
} else {
file_put_contents($logfile, $return, FILE_APPEND);
file_put_contents($logfile, serialize($output), FILE_APPEND);
}
}
}
}else{
file_put_contents($logfile, "No databases found to backup", FILE_APPEND);
}
exit(0);
If anybody can help, specially to read the output I will gladly appreciate it

Webhook handling with PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to build a webhook receiver.
I created this simple PHP-Script and uploaded it to my webhost:
$raw_payload = file_get_contents('php://input', true);
$payload = json_decode($raw_payload, true);
if($payload){
$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
fwrite(date('Y-m-d H:i:s', time()).PHP_EOL);
fclose($myfile);
}
then, in the App who sends the Webhook (actually Wekan) I entered the URL to the file:
http://myurl.com/dir/receiver.php
I sent some webhooks then, but nothing is written into the file.
The webhooks were sent correctly (I tested it with a webhook-tester and received some correct data there but not in my php-file).
The webhook data wich should be send looks like this (JSON):
{
text: '{{wekan-username}} moved "{{card-title}}" from "{{old-list-name}}" to "{{new-list-name}}"\nhttp://{{wekan-host}}/b/{{board-id}}/{{board-name}}/{{card-id}}',
cardId: '{{card-id}}',
listId: '{{new-list-id}}',
oldListId: '{{old-list-id}}',
boardId: '{{board-id}}',
user: '{{wekan-username}}',
card: '{{card-title}}',
description: 'act-moveCard'
}
What am I doing wrong here? (Can it be a problem with my webhost? The webhook-tester uses https, but for my php-file Im using http, does this cause the error?)
Your not passing the file resource handle to fwrite().
Then perhaps make your code more verbose, and keep an eye on the error log:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$raw_payload = file_get_contents('php://input');
$payload = json_decode($raw_payload, true);
if (is_array($payload)) {
$fh = fopen("log.txt", "a+");
if ($fh) {
fwrite($fh, date('Y-m-d H:i:s', time()).PHP_EOL);
fclose($fh);
} else {
trigger_error("Unable to open file!");
}
} else {
trigger_error("Invalid payload!");
}
} else {
trigger_error("Invalid request!");
}

Diff Tool which Outputs 1/0 // Yes/No [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'am searching for an Tool in !PHP! that will return maybe an Array or just something, with which i can lookup if there are any Changes.
Its beeing used to get Data from MySQL turning it into a JSON File and if the JSON File differs from the MySQL Output, then the file should be new generated.
So i just need to type a Function or something else, if there's been changes made, (Yes/No) do X.
Do you guys know any Tool that would work with my Idea?
Thanks for Helping me out.
Your question is vague but, if I understood right, here is an idea:
<?php
class Tool {
var $db; // you will have to provide a valid db connection
function __construct (& $db) {
$this->db = $db;
}
public function execute ($query, $file){
$arr = $this->fetch($query);
$dbJSON = json_encode($arr);
$fileJSON = file_get_contents($file);
if( md5($dbJSON) != md5($fileJSON) ){
$this->write($dbJSON, $file);
}
}
protected function fetch($sql) {
$arr = array();
$result = $this->db->query($sql);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$arr[] = $row;
}
// Free result set
$result->close();
}
return $arr;
}
protected function write ($content, $file) {
$fp = fopen('w+', $file);
fwrite($fp, $content);
fclose($fp);
}
}
?>
and a use case:
<?php
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}else{
$tool = new Tool($db);
$tool->execute('SELECT * FROM users','/com/user.json');
}
?>

Edit CSV Converting Rows into Columns [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am using Windows and working with CSV/XLS data. I have a data that need to edit with PHP, but I'm not sure how.
Here is sample the data:
code1,data1
D0001,X1235466
D0002,X1232265
D0003,X1235166
D0004,X5235466
D0005,X6232265
D0006,X7235166
.. and so on--about 20,000 lines.
I am trying to make the file look like this:
code1,data1,code2,data2,code3,data3
D0001,X1235466,D0002,X1232265,D0003,X1235166
D0004,X5235466,D0005,X6232265,D0006,X7235166
and so on, then save it to new CSV file. Thanks.
Alright, I was bored, so I wrote this. You really need to attempt writing the code before posting the question, though, and show your work.
Here goes:
<?php
$desiredColumns = 3;
$inputFd = fopen('data.csv', 'r');
$outputFd = fopen('output.csv', 'w');
$buffer = [];
// Write the CSV header.
fputcsv($outputFd, [
'code1', 'data1', 'code2', 'data2','code3', 'data3'
]);
//Skip header line.
fgetcsv($inputFd);
while (!feof($inputFd)) {
$line = fgetcsv($inputFd);
if (empty($line) || empty($line[0])) {
continue;
}
$line = array_map('trim', $line);
$buffer[] = $line;
// If our buffer has $desiredColumns in it, flush the buffer
// to our output file.
if (count($buffer) == $desiredColumns) {
outputCsv($outputFd, $buffer);
$buffer = [];
}
}
// If we had a total number of entries that is not a multiple
// of 3, we need to output the remaining records.
if (!empty($buffer)) {
outputCsv($outputFd, $buffer);
}
// Function for flushing a record buffer to the output file.
function outputCsv($outputFd, $buffer)
{
$outputData = [];
foreach ($buffer as $record) {
$outputData[] = $record[0];
$outputData[] = $record[1];
}
fputcsv($outputFd, $outputData);
}
Now, as an example of this being run:
$ cat data.csv
code1,data1
D0001,X1235466
D0002,X1232265
D0003,X1235166
D0004,X5235466
D0005,X6232265
D0006,X7235166
$ php so.php
$ cat output.csv
code1,data1,code2,data2,code3,data3
D0001,X1235466,D0002,X1232265,D0003,X1235166
D0004,X5235466,D0005,X6232265,D0006,X7235166

error in creating a file in PHP using file handling functions? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
someone could please tell why this code does not work? it does not create data.txt. and the file does not save anything.
<?php
$txt = "data.txt";
if(isset($_POST['info1']) && isset($_POST['info2']) && isset($_POST['info3']) && isset($_POST['info4']) && isset($_POST['info5']) && isset($_POST['info6'])) {
// check if both fields are set
//open file in read mode to get number of lines
$handle = fopen($txt, 'r');
//check file opened
if($handle) {
//get number of lines
$count = 1;
while(fgets($handle) !== false) {
$count++;
}
fclose($handle);
//open in append mode.
$handle = fopen($txt, 'a');
//prepare data to be writen
$txt = $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n";
//write data to file
fwrite($handle,$txt);
fclose($handle);
}
}
?>
In fopen function mode param with value r doesn't make file being created.
See fopen documentation.
Also the issue could be write permissions for user that runs that PHP script.
These is only my guesses. Anyway you should configure your PHP (in dev environment) to show you every error/warning in order to debug such issues. You can do that in php.ini file or straight in PHP file with this code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
You are first trying to open the file read only, and if that succeeds you close it and open it again with write access.
This will only work if the file already exists.
If the file doesn't exist, your text will not get written to it.
Move the closing bracket if if ($handle) { in front of the second fopen call.
if($handle) {
//get number of lines
$count = 1;
while(fgets($handle) !== false) {
$count++;
}
fclose($handle);
}
//open in append mode.
$handle = fopen($txt, 'a');
//prepare data to be writen
$txt = $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n";
//write data to file
fwrite($handle,$txt);
fclose($handle);
by the way, you can reduce this to three lines of code.
$lines = file($txt);
$count = sizeof($lines);
file_put_contents($txt, $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n", FILE_APPEND);
to check for multiple variables in isset create only one isset to check all veriables
change this
if(isset($_POST['info1']) && isset($_POST['info2']) && isset($_POST['info3']) && isset($_POST['info4']) && isset($_POST['info5']) && isset($_POST['info6']))
to
if(isset($_POST['info1'],$_POST['info2'],$_POST['info3'],$_POST['info4'],$_POST['info5'],$_POST['info6']))

Categories