Code Igniter Generating Query Result - codeigniter

I'm having trouble generating my query result.
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
Will this work?
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['0'];
echo $row['1'];
echo $row['2'];
}
Thank you.

As Edward mentioned, the array returned is an associative array. While there is no standard way to index into assoc array using integers, you could do it this way:
$resultarray = $query->result_array();
// get an array of keys in result
$keys = array_keys($resultarray[0]);
foreach ($resultarray as $row)
{
echo $row[$keys[0]];
echo $row[$keys[1]];
echo $row[$keys[2]];
}

$query->result_array() generates an associative array. You can't access it's elements by index.

Related

How to convert MySqli Loop Code Laravel controller

I want to work on a while loop in a foreach loop but I can't convert it to Laravel controller system. Please help.
foreach (range('a', 'z') as $i)
{
echo $i = strtolower($i);
$sql = "SELECT * FROM `list` Where name like '$i%' Limit 30";
$result = mysqli_query($con, $sql);
echo"<hr><h3>Name Starting with ".strtoupper($i)."</h3>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = $row['id'];
$name = $row['name'];
echo "<li>".$row['name']."</li>";
}
echo "<li>More</li>";
echo "</ul>";
}
The code in Laravel that I have is
foreach (range('a', 'z') as $i)
{
$list = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();
return view('pages.all', ['list' => $list]);
}
This code only gives data for names starting with alphabet "a" but won't proceed with the rest of the characters.
Store it on the array based on your search.
$list = array();
foreach (range('a', 'z') as $i) {
$list[$i] = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();
}
return view('pages.all', ['list' => $list]);
Customize your view, to showing the list against each character (a-z).
[Edit]
View file can be changed like below,
#foreach ($list as $keyI => $moredata)
<hr>
<h3>Author's Name Starting with "{{strtoupper($keyI)}}"</h3>
<ul class="tags-list">
#foreach ($moredata as $data)
<li>{{$data->name}}</li>
#endforeach
</ul>
#endforeach

Iterating through result set in Laravel controller

I am trying to simply iterate though a result set in laravel on the controller side. This is what I tried but I get the following error:
Cannot use object of type stdClass as array
Controller snippet:
$result = DB::select($query);
foreach($result as $r){
echo $r['email'];
}
I appreciate any help with this,
Thanks in advance!
You need to use it as an object:
$result = DB::select($query);
foreach($result as $r){
echo $r->email;
}
Or if for some reason you want to use it as array, you need to convert it first:
$result = DB::select($query)->toArray();
foreach($result as $r){
echo $r['email'];
}
After pulling data from database you can convert it to array but it is optional, it's depends on your necessity then you can simply use the foreach to loop through to each distinct object and get access their property
$data = DB:: table('categories')
->where('parent_id', $request->value)
->get()->toArray();
$output = '<option value="">Select '.ucfirst($request->dependent).'</option>';
foreach($data as $row){
$output.= '<option value="'.$row->id.'">'.$row->title.'</option>';
}
return response($output, 200);
The Laravel Collection class supports the standard methods for iterables: map, sort, filter etc. see: vendor/laravel/framework/src/Illuminate/Collections/Collection.php
if you're querying on a model:
$results = MyAwesomeModel::where('something' '=' 'other')->get();
//this is valid
$results->map(function($result) {
echo $result->field;
});
//this is also valid
for($i = 0; $i < sizeof($results); $i++){
echo $results[$i]->field;
}
I would suggest avoiding ->toArray() on hydrated results (instances of models) because you loose all the model properties.

codeigniter how to show data in functions

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
}
}

CodeIgniter change the field names result_array();

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
);
}

Query not working in CodeIgniter

function menuName ()
{
$this->viewData['page_title'] = "ContentManagement Systemt!";
$this->db->where('visible', 1);
$this->db->order_by("position", "ASC");
$query = $this->db->get('subjects');
$subjects = $query->result();
foreach ($subjects as $subject)
{
echo $subject->menu_name ."<br />";
$this->db->where('subject_id', $subject->id );
$query = $this->db->get('pages');
$pages = $query->result();
foreach ($pages as $page)
{
echo $page->menu_name ."<br />";
}
}
}
Why is my query not working? Please tell me.
You should always use foreach loops like the following:
$subjects = $query->result();
foreach ($subjects as $subject)
Your approach has a bad performance.
And maybe this already solves your problem - I couldn't test it right now . Your query variables are named equally and you're using $query in both of your foreach loops - this could maybe lead to some strange behaviour.
Why dont you echo the query like so:
echo $this->db->last_query()
To see what is going on with the results
Maybe the problem is there.

Resources