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
);
}
Related
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);
}
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;
}
My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}
I am trying to cycle through the results of my query to display in table format on my page.
What am I missing in my foreach and my echo to cycle through the results in my display table.
{source 0}
<?php
$user =& JFactory::getUser();
if (!$user->guest)
$name = $user->username;
$db =& JFactory::getDbo();
$query = $db->getQuery(true);
$query = "
SELECT image_url
FROM #__image_data
WHERE user_name = '$name'";
$db->setQuery($query);
$list = $db->loadObjectList();
foreach ($list as $item){
$item->image_url;
}
?>
<td><?php echo $item->image_url;?></td><br/>
<td><?php echo $item->image_url;?></td><br/>
<td><?php echo $item->image_url;?></td><br/>
{/source}
{source 0}
<?php
$user =& JFactory::getUser();
if (!$user->guest)
$name = $user->username;
$db =& JFactory::getDbo();
$query = $db->getQuery(true);
$query = "
SELECT image_url
FROM #__image_data
WHERE user_name = '$name'";
$db->setQuery($query);
$list = $db->loadObjectList();
foreach ($list as $item){
echo "<td>".$item->image_url."</td><br/>";
}
?>
{/source}
You can easily loops through and get the <td> as below.
Method 1 - Here you don't have to concatenate since you are using ""
$list = $db->loadObjectList();
foreach ($list as $item){
echo "<td> $item->image_url </td><br/>";
}
Method 2
$list = $db->loadObjectList();
foreach ($list as $item){
echo '<td>'.$item->image_url'.</td><br/>';
}
I have two main child under navigation in category tree as below images
I want to list category and subcategories for either Region or Activities, I have tried two different function for that
$collection = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('name')->load();
foreach ($collection as $cat) {
echo $cat->getName();
}
this will return all child from both Region and Actities and another function
$children = Mage::getModel('catalog/category')->getCategories(10);
foreach ($children as $category) {
echo $category->getName();
}
Reference link
this return only subcategories
I want to list all category, sub-categories and sub-subcategory and so on... for Region
Thank in advance
Try this one:
$rootcatId= 10;
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function get_categories($categories) {
$array= '<ul>';
foreach($categories as $category) {
$cat = Mage::getModel('catalog/category')->load($category->getId());
$count = $cat->getProductCount();
$array .= '<li>'.
'<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
$category->getName() . "(".$count.")</a>\n";
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')->getCategories($category->getId());
$array .= get_categories($children);
}
$array .= '</li>';
}
return $array . '</ul>';
}
echo get_categories($categories);