Laravel 4 MySQL query to array? - mysql

I'm using Laravel 4 and I need to take entries from my database, put them into an array and use them in a foreach loop in my view.
I'm not getting any errors but I'm also not getting anything from the database.
I'm trying to edit this page of a Laravel bundle to get products from the database, rather than statically.
This is my query from my Model
return $products = \DB::select('select * from products', array('sku', 'name'));
Controller...
public function getIndex()
{
// Get the products.
//
$products = Products::all();
// Show the page.
//
return View::make('shpcart::home')->with('products', $products);
}
This is my view
<pre>
<?php
print_r($products);
?>
</pre>
This is the result
Array
(
)
This works to insert into the database:
DB::insert('insert into products (sku, name) values (?, ?)', array('WS004', 'Test'));
This...
$products = DB::table('products')->get();
foreach ($products as $product)
{
echo $product->sku;
}
returns the error
Invalid argument supplied for foreach()
You can see it here...
http://wilsonswan.co.uk/collection
Thanks in advance.

You should not return $products as such.
You should perhaps do something like:
public function index()
{
$products = Products::where('sku', '=', 'name')->get();
return View::make('view', compact('products'));
}

try this:
public function getIndex() {
$db = DB::table('products as p')
->where('p.sku', '=', 'WS004');
$products = $db->get();
return View::make('shpcart::home')
->with('products', $products);
}

Related

Is it possible to combine whereHas with 'or' queries?

I'm trying to implement a filter system where, among other attributes and relationships, items are categorized. However, the challenge appears when combining OR queries with other filters using the regular and clause. The result grabs rows which I do not want and adds the or when the condition for that fails, thus polluting the final results with unwanted data.
<?php
class ProductSearch {
public $builder;
private $smartBuild; // this is the property I'm using to disable the alternation when other search parameters are present to avoid polluting their result
function __construct( Builder $builder) {
$this->builder = $builder;
}
public function applyFilterToQuery(array $filters) {
$pollutants = ['subcategory', 'subcategory2', 'category'];
$this->smartBuild = empty(array_diff( array_keys($filters), $pollutants)); // [ui=>9, mm=>4], [mm]
foreach ($filters as $filterName => $value) {
// dd($filters, $filterName );
if (method_exists($this, $filterName) && !empty($value) )
$this->$filterName( $value);
}
return $this;
}
public function location( $value) {
$this->builder = $this->builder
->whereHas('store2', function($store) use ($value) {
$store->where('state', $value);
});
}
public function subcategory( $value) {
$name = Subcategories::where('id', $value)->pluck('name');
$this->builder = $this->builder->where('subcat_id', $value);
if ($name->isNotEmpty() && $this->smartBuild) {
$names = preg_split('/\W\s+/', $name[0]);
if (!$names) $names = $name;
foreach ($names as $value)
$this->builder = $this->builder->orWhere('name', 'like', "%$value%");
}
}
}
You may observe from the above that making a request for categories searches products matching the category name. But on attempting to combine that alternate match with legitimate AND queries (in location for instance, the result tends to include matching locations OR matching names.
The desired result is ((matching name OR matching category) AND matching location). Is this possible?
I had similar situation like this few days ago about User and Posts.
Needed a list of posts which user has commented or participated in and which user owns.
So I did following on User model
//Get user created post or if user has participated in the post
$queryString->where(function ($query) use ($user_id) {
return $query->whereHas('participants', function ($q) use ($user_id) {
$q->where('user_id', $user_id);
})->orWhere('id', $user_id);
});
Hope this helps.

Database Error When trying to Join Table Codeigniter

So i want to fetch data from two tables.
But i got this error :
Here is my Query from Model:
public function tampil_edit($id) {
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
return $this->db->get_where('tb_m_notaris', $id);
}
Here is my Controller :
public function tampiledit($id) {
$id = ['id' => $id];
$title['title'] = 'Notaris | Edit';
$data['notaris'] = $this->m_notaris->tampil_edit($id)->result();
$this->load->view('template/headercss',$title);
$this->load->view('template/sidebar');
$this->load->view('template/navbar');
$this->load->view('master_data/notaris/edit', $data);
$this->load->view('template/footerjs');
}
Here Is what the $id contain:
Check your SQL
WHERE id = 45
^^
This id belongs to which table? I notice there are multiple table (tb_m_notaris,tb_m_user) with id column.
To call function
tampil_edit(45) {} # makesure $id is not an array
In model
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->from('tb_m_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id = tb_m_notaris.id');
$this->db->where('tb_m_notaris.id', $id);
return $this->db->get()->result();
}
You should try this.
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->get_where('tb_m_notaris', array('tb_m_notaris.id' => $id));
return $this->db->get()->row_array();
}
update this in your controller
$data['notaris'] = $this->m_notaris->tampil_edit($id);
you should pass like this in your controller
public function tampiledit($id) {
$id = ['tb_m_notaris.id' => $id];
$title['title'] = 'Notaris | Edit';
$data['notaris'] = $this->m_notaris->tampil_edit($id);
$this->load->view('template/headercss',$title);
$this->load->view('template/sidebar');
$this->load->view('template/navbar');
$this->load->view('master_data/notaris/edit', $data);
$this->load->view('template/footerjs');
}
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->from('tb_m_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->where('tb_m_notaris.id', $id);
$query = $this->db->get();
return $query->result_array();
}
You need to update your query to this.
As id column exists in both the tables, you need to explicitly provide which table id you want to connect to by mentioning the table name.

where condition in Codeigniter

i am trying to fetch data from the table which has some foreign keys by using codeigniter's active records. i haven't get any result. my question is where i'm going wrong here is my code in model.
public function fetch_customer()
{
$s = 'customer.stb_id';
$w_array = array('set_top_box.stb_id' => $s );
$customers = $this->db->select('customer.c_name,customer.acc_no,customer.stb_id,set_top_box.stb_no,customer.mobile_no,customer.subscription_amount,customer.c_status')
->from('customer,set_top_box')
->where($w_array)
->get();
return $customers->result();
}
Hello you can not add multiple table name in form () clause you use join() like this
public function fetch_customer()
{
$s = 'customer.stb_id';
$w_array = array('set_top_box.stb_id' => $s );
$customers = $this->db->select('customer.c_name,customer.acc_no,customer.stb_id,set_top_box.stb_no,customer.mobile_no,customer.subscription_amount,customer.c_status')
->from('customer')
->join('set_top_box','here on clause ')
->where($w_array)
->get();
return $customers->result();
}

JOIN works in SQL not in Drupal

I'm trying to make a module for Drupal 7.x. At a certain point I want to use a sql query (JOIN). When I try the query in MYSQL it works. But when I want to try it in Drupal, the array is empty.
So I guess there is a difference between the sql query and the drupal query (mayby the implemantion is different).
SQL Query
SELECT * FROM friends
INNER JOIN users
ON friends.uid=users.uid
Drupal implementation
function project_myfriends(){
// Use database API to retrieve tasks
$query = db_select('friends', 'f');
$query->join('users', 'u', 'f.uid = u.uid'); // JOIN
$query->fields('u', array('name'))
->execute();
return $query;
}
/**
* Implements hook_block_view().
*/
function project_block_view($delta = ''){
switch ($delta) {
case 'project':
$block['subject'] = t('My Friends');
// Use our custom function to retrieve data
$result = project_myfriends();
$items = array();
var_dump($result);
foreach($result as $friend){
$items[] = array(
'data' => $friend->name,
);
}
// No tasks
if (empty($items)) {
$block['content'] = t('No friends.');
}
else {
// Pass data trough theme function
$block['content'] = theme('item_list', array(
'items' => $items));
}
}
return $block;
}
Thx in advance
You forgot to fetch your result query:
$result = project_myfriends()->execute()->fetchAll();
var_dump($result);

Output query to csv, codeigniter

I currently have a report that give me the users ID number and their email address, But I would like to make this in a CSV file instead of tables and rows like I currently have.
Here is my controller
function View_Email_E()
{
$data = array();
if($query = $this->report_model->View_Email_English())
{
$data['records'] = $query;
}
$data['main_content'] = 'view_all_email_english';
$this->load->view('includes/template', $data);
}
Here is my model
function View_Email_English()
{
$query = $this->db->where(array('Dial_Up' => '0', 'Language' => 'English', 'Membership_Status' => 'Active'));
$query = $this->db->like('Email', '#');
$query = $this->db->get('Membership');
return $query->result();
}
For some reason my view is not being shown in code mode, but it is an auto generated table using these this snippet of code. Each row returns ID and Email from the database.
<?php if(isset($records)) : foreach($records as $row) : ?>
How can I make a CSV file with just ID and email fields?
Thanks
I think you can use the csv_from_result function in dbutil to do it. Try something like this:
$csvContent = $this->dbutil->csv_from_result($query);
if ( ! write_file('./path/to/file.csv', $csvContent)) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
http://codeigniter.com/user_guide/database/utilities.html#csv
Add
$this->db->select(array('ID','Email'));
To your View_Email_English function.