Debug Codeigniter Shoppincart Functions: - codeigniter

Can I have some help with this, please. This is a Codeigniter script MVC. There is a Controller "Function add to cart" with a Model: "Function get_products" in Models. I cannot see what is wrong here and why the function get_products doesn't execute. Could someone help me please.
This is the Model: get_product which connects to database:
function get_product()
{
$product_id = $this->input->post(‘product_id’);
$query = $this->db->select(‘product_id, product_name, description, price, photopath’);
$query = $this->db->from(‘product’);
$query = $this->db->where(‘product_id’, $product_id);
$query = $this->db->get(’‘);
return $query->result_array();
}
This is the Controller called Function add_cart, which add products to the "shopping cart view":
public function add_cart()
{
$thisProduct = $this->Cart_model->add_product();
if($thisProduct->num_rows() > 0)
{
$data = array(‘id’ => $thisProduct[‘product_id’],
‘qty’ => 1,
‘price’ => $thisProduct[‘price’],
‘name’ => $thisProduct[‘product_name’],
‘description’ => $thisProduct[‘description’]
);
$this->cart->insert($data);
}
$this->load->view(“site_header”);
$this->load->view(“site_nav”);
$this->load->view(“shoppingcart”, $data);
$this->load->view(“site_footer”);
}

you make many mistakes.
read here: http://codeigniter.com/forums/viewthread/128969/

Related

Codeigniter : array to string conversion error

Here is my model:
public function count_diabetic(){
$query = $this->db->query("Select count(diabetic) as count_diabetic from member where diabetic is not NULL");
return $query->result_array();
}
public function count_hypertensive(){
$query = $this->db->query("Select count(hypertensive) as count_hypertensive from member where hypertensive is not NULL");
return $query->result();
}
here is my controller:
public function home(){
$this->load->model('Jsv_model');
$data = array(
'count_diabetic' => $this->Jsv_model->count_diabetic(),
'count_hypertensive' => $this->Jsv_model->count_hypertensive()
);
$this->session->set_userdata($data);
$this->load->view('home');
}
Here is my view with in php tag:
echo $this->session->userdata('count_diabetic');
But Here it shows error that array to string conversion error..
please help me
Inside count_diabetic() you should change $query->result_array()
into
$query->row()->count_diabetic,
it would return number of count only not array.
Do it to count_hypertensive() too.
In PHP, you can display arrays by using the print_r function instead of echo.
For example, you have to change your code to:
print_r($this->session->userdata['count_diabetic']);
You are doing it wrong in this line.
echo $this->session->userdata('count_diabetic');
What should you do?
// To Set a Data in Session
$session_data = array(
'count_diabetic' => $this->Jsv_model->count_diabetic(),
'count_hypertensive' => $this->Jsv_model->count_hypertensive()
);
$this->session->set_userdata('user_data', $session_data);
// To get the session data
$session_data = $this->session->userdata('user_data');
$user_name = $session_data['username'];
$count_diabetic = $session_data['count_diabetic'];
$count_hypertensive = $session_data['count_hypertensive'];

Rewriting AutoSuggest (Minisearch) of Magento

I been trying for hours now to successfully rewrite Magento's build-in Autosuggest Function so it displays productnames instead of query history entries. I want nothing fancy, no product pictures and whatnot, just plain product name suggestions.
So to get the productnames, I created under app/code/local/Aw the folder CatalogSearch/Model and there created a file named Query.php. Inside that file I have the following class and rewritten method:
class Aw_CatalogSearch_Model_Query
extends Mage_CatalogSearch_Model_Query {
public function getSuggestCollection() {
$collection = $this->getData('suggest_collection');
if (is_null($collection)) {
$collection = Mage::getModel('catalog/product');
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($collection);
$collection->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('name', array('like' =>
'%'.$this->getQueryText().'%'))
->addExpressionAttributeToSelect('query_text', '{{name}}', 'name')
->addAttributeToSort('name', 'ASC')
->setPageSize(10)
->addStoreFilter($this->getStoreId());
$this->setData('suggest_collection', $collection);
}
return $collection;
}
};
I created the module xml file in app/etc/modules/ and the module configuration in app/code/local/Aw/CatalogSearch/etc/config.xml
All good so far, the overwritten method getSuggestCollection() is executed.
The problem comes in app/code/core/Mage/CatalogSearch/Block/Autocomplete.php, in the getSuggestData() method.
public function getSuggestData()
{
if (!$this->_suggestData) {
$collection = $this->helper('catalogsearch')->getSuggestCollection();
$query = $this->helper('catalogsearch')->getQueryText();
$counter = 0;
$data = array();
foreach ($collection as $item) {
$_data = array(
'title' => $item->getQueryText(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => $item->getNumResults()
);
if ($item->getQueryText() == $query) {
array_unshift($data, $_data);
}
else {
$data[] = $_data;
}
}
$this->_suggestData = $data;
}
return $this->_suggestData;
}
When it iterates over the collection, I get a
Call to a member function getQueryText() on a non-object ...
The point I do not understand is that I have defined an alias field named 'query_text' in the collection query inside the getSuggestCollection() method. Even when I used something like getData('query_text') or $item->getQuery_text() to get the data of this field is not working.
I have the strong feeling, that the collection object is not valid as it supposed be within the getSuggestData() method of Mage_CatalogSearch_Block_Autocomplete class.
Can anybody point me out how to solve this issue? Is it not possible as above way to gather suggestions from the products collection and pass these to Autocomplete.php?
This is my first magento project, so please bear with me! I am really lost on this one!
Any hint is greatly apprecitated.
Using Magento 1.7.0.2 for this project.
Well, I found a solution. For anyone who might be interested in this, the problem stated in my question is located in the following lines
$collection = Mage::getModel('catalog/product');
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($collection);
$collection->getCollection() ... // continue method chaining ...
I changed the code, so that the constructor and methods are chained all together, like this:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('name') ... // continue method chaining
...
I added the filters for product_status, cataloginventory/stock and catalog/product_visibility with singleton calls right after the collection is available
In that way, everything works as expected.
For anyone else wanting to do something similar, I just rewrote app/code/core/Mage/CatalogSearch/Block/Autocomplete.php to my own module and made the search results query the sku and return product names. Your mileage may vary, however, my sku codes are sensible names rather than random digits so this worked for me.
public function getSuggestData()
{
if (!$this->_suggestData) {
$collection = $this->helper('catalogsearch')->getSuggestCollection();
$query = $this->helper('catalogsearch')->getQueryText();
$counter = 0;
$data = array();
foreach ($collection as $item) {
$_data = array(
'title' => $item->getQueryText(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => $item->getNumResults()
);
if ($item->getQueryText() == $query) {
array_unshift($data, $_data);
}
else {
$data[] = $_data;
}
}
// Get products where the url matches the query in some meaningful way
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('type_id', 'configurable')
->addAttributeToFilter('sku',array('like'=>'%'.$query.'%'))
->load();
foreach($products as $product) {
$_data = array(
'title' => $product->getName(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => 1
);
// if ($item->Name() == $query) {
// array_unshift($data, $_data);
// }
// else {
$data[] = $_data;
// }
}
$this->_suggestData = $data;
}
return $this->_suggestData;
}
I did not need to rewrite Mage_CatalogSearch_Model_Query, just the code for the suggestions.

codeigniter error using JOIN to select single row

Im trying to get joins to work when selecting a single row. here is my code:
model:
function view($id) {
$this->db->select('c.name
,c.phone
,c.active
,c.website
,c.date_acquired
,con.firstName');
$this->db->from('company c');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->row_array();
controller:
public function view($id)
{
$this->load->model('Company_model');
$data['data']= $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
the error im getting is:
Fatal error: Call to a member function row_array() on a non-object in
/home/techf/public_html/application/models/company_model.php on line
35
and line 35 in the above code is:
$query = $this->db->get()
is this not correct when dealing with joins and a row array?
**
edit 1
**:
Here is my controller:
public function view($id)
{
$this->load->model('Company_model');
$data = $this->Company_model->view($id)->row();
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
and my model:
function view($id) {
$this->db->select('*');
$this->db->from('company');
$this->db->join('contacts con','c.primary_contact = con.id','left');
$this->db->where('id', $id);
return $this->db->get('company');
}
but now im am getting error:
Fatal error: Call to a member function row() on a non-object in
/home/techf/public_html/application/controllers/company.php on line 21
Here you go model code
public function get_joins($table,$value,$joins,$where,$order_by,$order)
{
$this->db->select($value);
if (is_array($joins) && count($joins) > 0)
{
foreach($joins as $k => $v)
{
$this->db->join($v['table'], $v['condition'], $v['jointype']);
}
}
$this->db->order_by($order_by,$order);
$this->db->where($where);
return $this->db->get($table);
}
and in your controller aceess it like
$value=('restaurantorders.*,restaurant.Name,restaurant.CurrencyId,currency.*,orderpaymentdetail.Gateway ');
$joins = array
(
array
(
'table' => 'tk_restaurant',
'condition' => 'restaurant.Id = restaurantorders.RestaurantId',
'jointype' => 'inner'
),
array
(
'table' => 'tk_currency',
'condition' => 'restaurant.CurrencyId = currency.Id',
'jointype' => 'inner'
),
array
(
'table' => 'tk_orderpaymentdetail',
'condition' => 'restaurantorders.Id = orderpaymentdetail.OrderId',
'jointype' => 'inner'
),
);
$data['order_detail'] = $this->general_model->get_joins($data['tbl'],$value,$joins,array('OrderStatus'=>'Confirm','restaurantorders.Id'=>$orderid),'restaurantorders.Id','desc')->row();
note that on the model i test first if num_rows() is greater than 1 before sending on the row and if not return false.
Note that on my this->db->get i removed the name of the table, because you already added it on the from method.
$this->db->select('*')
->from('company c');
->join('contacts con','c.primary_contact = con.id','left');
->where('id', $id);
$query = $this->db->get();
return $query->num_rows() >= 1 ? $query->row() : FALSE;
on your COntroller
on on the data variable you forgot to add a key, this will be used when you access the variable/object on you're view, example is $data['contacts']
public function view($id)
{
$this->load->model('Company_model');
$data['contacts'] = $this->Company_model->view($id);
$this->load->view('templates/header');
$this->load->view('company/view', $data);
$this->load->view('templates/footer');
}
on your VIEWS
access the contacts key that you assigned earlier on you're controller.
<?
if(!empty($contacts))
{
print_r($contacts);
}else{
echo 'No data';
}
?>
to show the structure of your query on a standard MySQL query
you could comment out the return on you're model and add this snippets of code just after the $this->db->get() method.
echo $this->db->last_query();
die();
This will echo out what query was made, and you can run it on phpmyadmin and compare if the values returned are right.
can you try it like this maybe?
model: (i'm not sure in which table is id and in which primary_contact, so change that if i made a mistake)
function view($id) {
$this->db->join('contacts','company.primary_contact = contacts.id','left')
->where('id', $id);
$query = $this->db->get('company');
return $query->row();
}
in controller call it like this:
$data['result'] = $this->company_model->view($id);
then access object in view:
<?=$result->id?> (etc.)

Array from Controller to model [codeIgniter]

here's my problem:
Codeigniter's doc says this :
<?php
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
?>
I just want to pass conditions to my where clause from controller to model so :
Controller
<?php
$condition = array('id' => $id_user)
$data['info_user'] = $this->user_model->get_user($condition);
?>
Model
public function get_user($condition)
{
$q = $this
->db
->where($condition)
->get('users');
if($q->num_rows > 0)
{
return $q->row();
}
}
This return : SELECT * FROM (users) WHERE 3 IS NULL
But when I put my array directly in the model ($
There is no need to pass an array and I'm not even positive that it can be done the way you're trying to do it. Just pass the value itself to the model as below. Answer edited to show multiple variables.
Controller:
$data['info_user'] = $this->user_model->get_user($id_user,$user_login);
Model:
public function get_user($id_user,$user_login)
{
$q = $this
->db
->where('id_user',$id_user)
->or_where('user_login',$user_login);
->get('users');
if($q->num_rows == 1)
{
return $q->row();
}
}
As a side note when you want a single result from your database, as in retrieving a user ALWAYS check for a single result and not > 0. You want to ensure you're only getting one user back.

codeigniter view, add, update and delete

I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.

Resources