I need to export results from a MySQL query into a csv file in codeigniter.
This is the model:
public function export_csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$file_name = 'BVN_REPORTS'.date("Y-m-d h-i-s").'.csv';
$query = 'SELECT account_name as "Account Name",
api_account_name as "Verified Name",
account_num "Account Number",
bvn "Bank Verification Number (BVN)", bank_name as "BANK NAME"
from ew_employees where bvn is not null
ORDER BY bank_name ';
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
if(force_download($filename, $data)){
echo 'Done';
}
else {echo 'Not Done';}
}
And this is the controller:
public function get_csv()
{
$this->load->model('employees_model');
$this->employees_model->export_csv();
}
The result is always 'Not Done'...how can i force a csv download of the query results.Thanks
According to the Question title let me Answer the question.Generally it may help other when visit here.
what i generally do when exporting data to csv.
function data_to_csv($data, $headers = TRUE, $filename= "")
{
if ( ! is_array($data))
{
show_error('invalid Data provided');
}
$array = array();
if ($headers)
{
$array[] = array_keys($data[0]);
}
foreach ($data as $row)
{
$line = array();
foreach ($row as $item)
{
$line[] = $item;
}
$array[] = $line;
}
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=\"$filename".".csv\"");
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
foreach ($array as $array) {
fputcsv($handle, $array);
}
fclose($handle);
exit;
}
controller
$result = $this->registration_model->exportToCsv();
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=\"application".".csv\"");
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
fputcsv($handle, array('Sr No.', 'Apply for', 'Name', 'mobile', 'email_id', 'work_experinece', 'pan', 'refrence', 'pro_img1', 'pro_img2', 'created_at'));
$i = 1;
foreach ($result as $data) {
fputcsv($handle, array($i, $data["apply_for"], $data["full_name"], $data["mobile"], $data["email_id"], $data["work_experinece"], $data["pan"], $data["refrence"], $data["pro_img1"], $data["pro_img2"], $data["created_at"]));
$i++;
}
fclose($handle);
exit;
Model
$this->db->select("apply_for,full_name,mobile,address,email_id,work_experinece,pan,refrence,pro_img1,pro_img2,created_at");
$this->db->order_by("app_id", "DESC");
$this->db->from("tablename");
$query = $this->db->get();
return $query->result_array();
I added a line to Abdul Manan's answer to deal with UTF-8 characters :
foreach ($array as $array) {
fputs($handle, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($handle, $array);
}
Related
I am trying to use image url instead of base64. i kindof figured a way how to get images out of the editor and save it inside the directory, but i am trying to insert it into database. i get this error.
Object of class DOMElement could not be converted to string
below i have added the store function inside my controller
public function store(Request $request)
{
//
$data = $request->all();
if (!$request->has('published')) {
$data['published'] = 0;
} else {
$data['published'] = 1;
}
if (!$request->has('featured')) {
$data['featured'] = 0;
} else {
$data['featured'] = 1;
}
$img = null;
if ($request->hasfile('title_img')) {
$image = $request->file('title_img');
$name = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/blogs/', $name);
$img = '/uploads/blogs/' . $name;
}
/* summernote */
$detail=$data['description'];
$dom = new \DomDocument();
$dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
$data = $img->getAttribute('src');
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name= "/uploads/summernote/" . time().$k.'.jpeg';
$path = public_path() . $image_name;
file_put_contents($path, $data);
$img->removeAttribute('src');
$img->setAttribute('src', $image_name);
}
$detail = $dom->saveHTML();
/* summernote */
$data['title_img'] = $img;
$data['user_id'] = auth()->user()->id;
$title = $data['title'];
$data['slug'] = Str::slug($title);
auth()->user()->posts()->create($data);
return Redirect::route('admin.blog.index')->withSuccess('Whoopie!! New Blog Added!');
}
I hope i can get some help regarding this. Thanks in advance
I have made a query that gets customer's orders. Can I get customer gender based on this query? If not, how can I get customer gender? This is the code I have so far:
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$productId = 297;
$orders = Mage::getModel('sales/order')->getCollection();
$orders
->getSelect()
->joinLeft(
array(
'order_item' =>Mage::getSingleton('core/resource')->getTableName('sales/order_item')),
'order_item.order_id = main_table.entity_id',
array('product_id'=>'product_id'))
->where('product_id=?', $productId)
->group('main_table.entity_id')
->order('main_table.entity_id DESC');
$fields = "date,company,name,country,city,address,postcode,itemname,quantity,price,sku \n";
foreach($orders as $order):
$order->getData();
$order->getIncrementId();
$billingAddress = $order->getBillingAddress();
$shippingAddress = $order->getShippingAddress();
$billingStreet = $billingAddress->getStreet();
$countryCode = $billingAddress->getCountry();
$country = Mage::getModel('directory/country')->loadByCode($countryCode);
$fields .=
date('Y-m-d',strtotime($order->getCreatedAt())).','.
$billingAddress->getCompany().','.
$billingAddress->getName().','.
$country->getName().','.
$billingAddress->getCity().','.
$billingStreet[0].','.
$billingAddress->getPostcode().','.
$order->getShippingDescription() .',';
foreach ($order->getAllItems() as $itemId => $item):
$itemname = $item->getName();
$itemname = str_replace('&', " ", $itemname);
$fields .=
$itemname. ','.
$item->getQtyOrdered().','.
$item->getPrice().','.
$item->getSku().',';
endforeach;
$fields = rtrim($fields, ',');
$fields .= "\n";
endforeach;
$name = date('d-m-Y-H-i-s');
$output = fopen('backend/assets/csv/' . $name . '.csv', 'w');
fwrite ($output,$fields);
fclose ($output);
foreach($orders as $order){
$customer = $order->getCustomer();
Mage::log($customer->getGender());
}
if this does not work then:
foreach($orders as $order){
$customer = $order->getCustomer();
$customerObj = Mage::getModel('customer/customer')->load( $customer->getEntityId());
Mage::log($customerObj->getGender());
}
I use CI form with form_dropdown helper and tried to pull Mysql data into its options, from the below code, its only retrieve the last record from db into the option list?
please advise what is wrong with my code?
Model
public function getStates() {
$query = $this->db->get('states');
$return = array();
if($query->num_rows() > 0){
$return[''] = 'please select';
foreach($query->result_array() as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}
Controller
$this->load->model('db_model');
$data['options'] = $this->db_model->getStates();
$this->load->view('create_new', $data);
View
$state = array(
'name' => 'state',
'id' => 'state',
//'value' => set_value('state', $state)
);
<?php echo form_label('State', $state['id']); ?>
<?php echo form_dropdown($state['name'], $options); ?>
<?php echo form_error($state['name']); ?>
<?php echo isset($errors[$state['name']])?$errors[$state['name']]:''; ?>
send full query result from the model to the view like this
Model
public function getStates() {
$query = $this->db->get('states');
return $query->result();
}
let the controller as it is and now you can populate states in dropdown like this:
View
<?php
foreach($options as $opt){
$options[$opt->state_id]=$opt->state_name;
}
echo form_dropdown($state['name'], $options);
?>
Try this:
function getStates() {
$return = array();
$query = $this->db->get('states')->result_array();
if( is_array( $query ) && count( $query ) > 0 ){
$return[''] = 'please select';
foreach($query as $row){
$return[$row['state_id']] = $row['state_name'];
}
}
return $return;
}
I am using $data = $query->result_array(); but I would need to change my fields name from first_name to first name.
I looked up found this....
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
would I want to do something like this?
foreach ($query->result_array() as $row)
{
$row = str_replace("_", " ", $row);
}
$data = $row;
if you need then a new array you can easly do:
foreach ($query->result_array() as $key=> $value)
{
$data[] = array(
str_replace("_", " ", $key)=>$value
);
}
my controller is
$data['qna'] = $this->Ivote_model->get_qa();
view
foreach($qna as $k=>$v){
echo $v['question']. '<br/>';
echo '-' .$v['answer'] . '<br/>';
model
function get_qa(){
$data = array();
$this->db->select('*');
$this->db->where('v_questions.id',1);
$this->db->from('v_answers');
$this->db->join('v_questions','v_questions.id = v_answers.question_id');
$q = $this->db->get();
if($q->num_rows > 0){
foreach($q->result_array() as $row){
$data[] = $row;
}
}
$q->free_result();
return $data;
}
my html page shows
What is your favorite food?
-Sushi
What is your favorite food?
-Burgers
What is your favorite food?
-kodo
what i want is
What is your favorite food?
-Sushi
-Burgers
-koddo
please help me how do i achieve that ?
I would do a couple of things:
function get_qa(){
/* ... */
if($q->num_rows > 0){
foreach($q->result_array() as $row){
// create an associative array of question => answer.
// that ensures 1-1 mapping.
if(!isset($data[$row['question']])) $data[$row['question']] = array();
$data[$row['question']][] = $row['answer'];
}
}
/* ... */
}
Then, in the view:
foreach($qna as $k=>$v){
echo $k. '<br/>';
foreach( $v as $ans ){
echo '-' .$ans . '<br/>';
}
}