WPDB exporting custom query to csv - file not being created - database

I'm using the following code to export a custom MYSQL query to CSV. The data and column headers are working fine (print $csv_output; is exactly as I expect) but the actual CSV file is not being created.
What am I getting wrong?
function generate_csv(){
global $wpdb;
$table_name = $wpdb->prefix."ck_shipment";// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );
// get column names
$query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";
$columnNamesList = $wpdb->get_results($query);
foreach ( $columnNamesList as $column_name ) {
$csv_output.=$column_name->COLUMN_NAME.",";
}
// remove last additional comma
$csv_output = substr($csv_output,0,strlen($csv_output)-1);
// start dumping csv rows in new line
$csv_output.="\n";
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
print $csv_output;
exit;
}
?>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<br /><input type="submit" name="export" value="export" class="button-primary">
</form>
<?php
if (isset($_POST['export'])) {
generate_csv();
}
Thanks!

Related

Laravel: Updating multiple files in array

I was able to store and save multiple files in the array into the database, as well as updating the form data. However, the problem now is it returns this error when I update the form without updating the file.
count(): Parameter must be an array or an object that implements Countable
Does anyone know what should I do for my update function or value in my blade file so that it won't delete the file elements?
--------------------------------------------- UPDATED ---------------------------------------------
public function update(Request $request, $id)
{
$data = $request->all();
$data = $this->saveEmptyData($data);
$c = Document::find($id);
$fileData = [];
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('storage/documents');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc = json_encode($fileData);
$c->file = $doc;
$c->name = $request->name;
$c->price = $request->price;
$c->publish = $request->publish;
}
//else {
// redirect()->back()->with('errors', 'File is required!');
//}
$c->save();
return redirect()->route('product.index')->with('success', 'Document updated successfully');
}
Blade
<form method="POST" action="{{ route('document.update', $doc) }}" enctype="multipart/form-data">
<fieldset>
....
<div class="form-group">
<label>Document</label>
<div class="input-group-append">
<label for="upload_file">Upload</label>
<input id="upload_file" type="file" name="file[]" value="{{ isset($doc) ? $doc['file'] : '' }}" multiple>
</div>
</div>
</fieldset>
</form>
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc= json_encode($fileData); //replace $doc['file'] with $doc
$c->file=$doc;
}
$c->save();
//not required to declare $fileData ;
enctype="multipart/form-data" in form tag
if(count($request->file)>0)
{
foreach($request->file as $file)
{
$path = public_path('documents/');
$fileName = time().'_'.$file->getClientOriginalName();
$file->move($path, $fileName);
if ($c->file)
{
File::delete($path.'/'.json_decode($c->file)[0]);
}
$fileData[] = $fileName;
}
$doc['file'] = json_encode($fileData);
}

how to upload image to folder and path ot db in cakephp controller

i have written code in controller to move the uploaded file to folder ,but it was not working ,my code is
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a, '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
i think this line 'if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){ ... } was not working ,through this code i am able to store the '0 in my database i.e else part of the code.
how to move the uploaded image to folder and path to my database field..plz help me any one...!
my script code is
function addAdminList(){
var branchId = $('#branchId').val();
var branchName = $('#branchName').val();
var curiculumName = $('#curiculumName').val();
var owner = $('#owner').val();
var startdate = $('#startdate').val();
var phone = $('#phone').val();
var desc = $('#desc').val();
var address = $('#address').val();
var timings = $('#timings').val();
var image = $('#image').val();
if(!$("#addClsGrpFrm").validationEngine('validate')){
return false;
}
$('.overlay').show();
$.ajax({
url : '<?php echo BASE_PATH; ?>adminAjax/addAdminList',
type : 'POST',
data : {
branchId : branchId,
branchName : branchName,
curiculumName : curiculumName,
owner : owner,
startdate : startdate,
phone : phone,
desc : desc,
address : address,
timings : timings,
image : image
},
success : function(res){
$('.overlay').hide();
if(res == 0){
}
parent.$.colorbox.close();
oTable.fnDraw();
return false;
},
error : function(res){
alert('Server Error Occurred');
}
});
}
my form is
<form id="addClsGrpFrm" method="post" action="#" onsubmit="return disableFrmSubmit()">
<div class="flash_msg"><?php echo $this->Session->flash(); ?></div>
<input type="hidden" name="data[branch][id]" readonly id="branchId" value="0">
<div class="login-form">
<label>Shop Image</label>
<input type="file" id="image" data-prompt-position="topLeft:200" name="data[branch][image]" placeholder="" class="validate[required]" />
.....
</div>
<div class="login-form">
<input type="button" onclick="addAdminList()" class="login-btn" value="Submit">
</div>
<div class="clear"></div>
</form>
Some suggestions while submitting your form :
Use FormData when submitting your form rather than appending them one by one.
The extension extraction process that you are using in your controller may not save some files with "." in their filename.
I have created a test form for your knowledge.This is the form:
<form id="testForm" method="post" action="<?php echo 'http://localhost/blog/users/test'; ?>">
<input type="file" name="image" id="image">
<input type="submit" value="Submit">
</form>
You can use FormData like so:
$('#testForm').on('submit', function(event) {
event.preventDefault();
var form_data = new FormData($(this)[0]); // this will get all your form's inputs
$.ajax({
url:"<?php echo 'http://localhost/blog/users/test.json'; ?>", // you can use your form action URL here
type:'POST',
data:form_data,
processData: false,
contentType: false
});
});
and finally in your controller:
public function test() {
if ($this->request->is('post')) {
if (!empty($this->request->data['image']['tmp_name']) && is_uploaded_file($this->request->data['image']['tmp_name'])) {
$filename = basename($this->request->data['image']['name']);
$imagePath = WWW_ROOT . DS . 'documents' . DS . $filename; // save the file where you wish
move_uploaded_file(
$this->request->data['image']['tmp_name'],
$imagePath // save $imagePath in your database
);
}
}
}
You can use $imagePath to save in your database and as for your file extension process you can use this function as it will get the filetype even if the filename has a "dot" in it :
public function findFileTypeAndName($filename)
{
$split_point = '.';
$parts = explode($split_point, $filename);
$last = array_pop($parts);
$fileNameAndType = array(implode($split_point, $parts), $last);
return $fileNameAndType;
}
$this->layout = "ajax";
if($this->request->data){
$postArr = $this->request->data;
$a = $postArr['image'];
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
if(move_uploaded_file($a['tmp_name'], WWW_ROOT . '/img/uploads/users/' . basename($a['name']))){
echo 'success';
$hai = 1;
}
else
{
echo 'failed';
$hai = 0;
}
}
.....
.....
......
$Curriculum = array();
$Curriculum['Shop']['image'] = $hai;
$this->Shop->save($Curriculum);
echo 0;
exit;
The issue is just that you tried to pass the image array to strrchr($a) instead of strrchr($a['name']) at this point:
$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
Then you also tried to pass $a which is an array into move_uploaded_file($a,...).
Check my corrections for that part of the code...

Codeigniter Model: How to use values from a query for further calculations?

i have a function in a model with the following query, and i want to make some calculations with value1, value2 and value3 outside the query. how to get the values out of this result()?
function ($id,$username$) {
$this->db->select("id,value1,value2,value3,value4");
$this->db->from("table1");
$this->db->where("username=$username and id = $id");
$query=$this->get();
$result = $query->result();
$result['$testvalue'] = (value1 * value2/113) + value3;
return $result; }
can someone help? i already found out how to use values from a table, but not from a query!
ok now i know how to use row_array.
i call the row_array in the controller
$data = $this->model_testmodel->testfunction($id, $username);
...
$this->load->view('pages/view_test', $data);
now i wanna know how the view would look like.
i tried many different ways.
in the moment i am stuck with ...
<?php foreach $data as $value: ?>
<label>Value1:</label>
<input type="text" name="value1" value="<?php echo $value['value1']; ?>">
<label>Value2:</label>
<input type="text" name="value2" value="<?php echo $value['value2']; ?>">
...
<?php endforeach; ?>
but i get two errors:
Message: Undefined variable: data
Message: Invalid argument supplied for foreach()
Try this...
function ($id,$username)
{
$this->db->select("id,value1,value2,value3,value4");
$this->db->from("table1");
$this->db->where(array('id'=>$id,'username'=>$username));
$query=$this->db->get();
$result = $query->row();
$testvalue = (($result->value1 * $result->value2/113) + $result->value3);
//test here
echo $testvalue;
$res = array();
$res['testvalue'] = $testvalue;
$res['value1'] = $result->value1;
$res['value2'] = $result->value2;
$res['value3'] = $result->value3;
return $res;
}
It returns $res as array.Easy to execute of you got problem comment.. if it works accept.Lets enjoy..
Then make a function call and accept array in a variable..like this..
first load model then make function call.from your controller
$this->load->model('model_name');
$data= $this->model_name->function_name($id,$username);
//Fetch returned array like this..
echo $data['testvalue'];
echo $data['value1'];
//so on

Expanding Rows for Unique Checkboxes

I was just recently given a project for my job to write a script that compares two mysql databases and print out information into an html table. Currently, I am trying to insert a checkbox by each individual's name and when selected, rows pertaining to that individual will expand underneath the person's name. I am combining javascript into my script to do this, although I really have no experience is it. The problem I am having is that when any checkbox is selected, all the rows for each individual is expanding instead of the rows pertaining only to the one individual selected.
Here is my code so far:
PHP Code:
<?php
$link = mysql_connect ($server = "harris.lib.fit.edu", $username = "", $password = "") or die(mysql_error());
$db = mysql_select_db ("library-test") or die(mysql_error());
$ids = mysql_query("SELECT * FROM `ifc_studylog`") or die(mysql_error()); //not single quotes (tilda apostrophy)
$x=0;
$n=0;
while($row = mysql_fetch_array( $ids ))
{
$tracksid1[$x] = $row['fitID'];
$checkin[$x] = $row['checkin'];
$checkout[$x] = $row['checkout'];
$n++;
$x++;
}
$names = mysql_query("SELECT * FROM `ifc_users`") or die(mysql_error()); //not single quotes (tilda apostrophy)
$x=0;
while($row = mysql_fetch_array( $names ))
{
$tracksnamefirst[$x] = $row['firstName'];
$tracksnamesecond[$x] = $row['lastname'];
$tracksid2[$x] = $row['fitID'];
$tracksuser[$x] = $row['tracks'];
$x++;
}
$x=0;
foreach($tracksid2 as $comparename)
{
$chk = strval($x);
?>
JS Code:
$(window).load(function() {
$('.varx').click(function() {
$('.text').toggle(this.checked);
});
});​
PHP Code:
<?php
echo '<td><input id = "<?=$chk?>" type="checkbox" class="varx" /></td>';
echo '<td align="center">'.$comparename.'</td>';
echo'<td align="center">'.$tracksnamefirst[$x].'</td>';
echo'<td align="center">'.$tracksnamesecond[$x].'</td>';
$z=0;
foreach($tracksid1 as $compareid)
{
$HH=0;
$MM =0;
$SS =0;
if($compareid == $comparename)// && $tracks==$tracksuser[$x])
{
$SS = sprintf("%02s",(($checkout[$z]-$checkin[$z])%60));
$MM = sprintf("%02s",(($checkout[$z]-$checkin[$z])/60 %60));
$HH = sprintf("%02s",(($checkout[$z]-$checkin[$z])/3600 %24));
// echo'<td align="center">'.$HH.':'.$MM.':'.$SS.'</td>';
echo '</tr>';
echo '<tr>';
echo "<td id='txt' class='text' align='center' colspan='2' style='display:none'></td>";
echo "<td id='txt' class='text' align='center' style='display:none'>".$checkin[$z]."</td>";
echo '</tr>';
}
echo '<tr>';
$z++;
echo '</tr>';
}
$x++;
}
}
?>
Any help is appreciated and apologies if I am too vague on the subject. The username and password have been left out for security reasons.

Uploading multiple files userfile[] array?

I am trying to upload multiple images and I have a jquery plugin set up so I can browse for multiple files and select them.
The only problem I am having is accessing the file array in my controller, does anyone know how I can do this? Thanks.
view:
<input type="file" name="userfile[]" id="userfile" class="multi" />
I had this same issue on a project last year, after a bit of searching I found a perfect function.
I take no credit it for it, but cannot remmeber where I found it so if anyone knows please link back to the author.
Make sure the form has the files named like this
<input type="file" name="userfile"/>
<input type="file" name="userfile2" />
<input type="file" name="userfile3" /> ..etc
Or
<input type="file" name="userfile[]" />
The function..
function multiple_upload($upload_dir = 'uploads', $config = array())
{
$files = array();
if(empty($config))
{
$config['upload_path'] = '../path/to/file';
$config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
$config['max_size'] = '800000000';
}
$this->load->library('upload', $config);
$errors = FALSE;
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if( ! $this->upload->do_upload($key))
{
$data['upload_message'] = $this->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
$this->load->vars($data);
$errors = TRUE;
}
else
{
// Build a file array from all uploaded files
$files[] = $this->upload->data();
}
}
}
// There was errors, we have to delete the uploaded files
if($errors)
{
foreach($files as $key => $file)
{
#unlink($file['full_path']);
}
}
elseif(empty($files) AND empty($data['upload_message']))
{
$this->lang->load('upload');
$data['upload_message'] = ERR_OPEN.$this->lang->line('upload_no_file_selected').ERR_CLOSE;
$this->load->vars($data);
}
else
{
return $files;
}
}
Now it's been a while since I've used it so if you need any extra help setting it up just let me know.
To use Jquery multiple upload using html elements array [] developed as follows in the act of receiving data sobrescrevi the global variable $ _FILES PHP so that the function do_upload could read later. see:
#copy the original array;
$temp_array;
foreach($_FILES['fil_arquivo'] as $key => $val)
{
$i = 0;
foreach($val as $new_key)
{
$temp_array[$i][$key] = $new_key;
$i++;
}
//
}
$i = 0;
foreach($temp_array as $key => $val)
{
$_FILES['file'.$i] = $val;
$i++;
}
#clear the original array;
unset($_FILES['fil_arquivo']);
$upload_path = 'media/arquivos';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'doc|docx|xls|xlsx|ppt|pptx|pdf|txt|jpg|png|jpeg|bmp|gif|avi|flv|mpg|wmv|mp3|wma|wav|zip|rar';
$config['encrypt_name'] = true;
$this->upload->initialize($config);
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if($this->upload->do_upload($key))
{
$this->upload->data();
}
}
}
The HTML provided by ojjwood above will produce multiple input boxes. If you'd only like to have one input box but still upload multiple files, you need to include the attribute multiple="multiple" in your <input> element. The [] in name="userfile[]" allows the posted data to be an array and not just a single value.
On the Codeigniter/PHP side of things, you need to use $_POST['userfile] instead of $this->input->post('userfile') for working with arrays.

Resources