Returning NULL from query for datatables - php

I'm wondering what would be best to do. Right now I have running a query to see if I have any results returned and if none are returned I return NULL.
On my controller I send that resultset whether it be an object or NULL to my table and it echos the rows on the view page.
For my tables I am using the jquery datatables plugin. I'm trying to figure out how I can have it handle the data when the sent value is NULL that way it doesn't show me an error when it hits my foreach loop.
Controller:
$news_articles = $this->news_model->get_news_articles();
$this->data['news_articles'] = $news_articles;
Model:
/**
* Get news articles
*
* #return object
*/
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return NULL;
}
View:
$tmpl = array ( 'table_open' => '<table class="table" id="newsarticles-table">' );
$data = array('name' => 'newsarticles', 'class' => 'selectall');
$this->table->set_heading(form_checkbox($data), 'ID', 'Date', 'Title');
$this->table->set_template($tmpl);
foreach ($news_articles as $row)
{
$checkbox_data = array(
'name' => 'newsarticles',
'id' => $row->id
);
$this->table->add_row(form_checkbox($checkbox_data), $row->id, $row->date_posted, $row->article_title);
}
echo $this->table->generate();

I typically respond using JSON and then add a "success" type boolean and then check that value before trying to process any data. It also allows for an easy way to place an error message in the response if something goes wrong.

Just another idea
Model
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return FALSE;
}
Controller
$news_articles = $this->news_model->get_news_articles();
if(!$news_articles) $this->data['success'] = FALSE;
else
{
$this->data['news_articles'] = $news_articles;
$this->data['success'] = TRUE;
}
In the view
if($success)
{
foreach ($news_articles as $row)
{
//....
}
}
else echo "No results found !";

Just return an empty array from the model, if there are not results. That way your foreach won't break. It just won't loop over anything.

Related

how to pass the data in the post so that we can call the id?

how to pass the data in the post so that we can call the id ?
because we are trying to get the "qtopic_id" of the question but its not working and it keeps on giving me a null value.
I have tried declaring qtopic_id= 19 to see if its saving in the qtopic_id column.
I don't have to put a specific id value to save on the following column so that it wont save on that specific id only but instead it will save on its corresponding qtopic_id.
controller
public function addChoices(){
$this->form_validation->set_rules('ques','Question','required');
$this->form_validation->set_rules('ch_des1','Choices','required');
$this->form_validation->set_rules('ch_des2','Choices','required');
$this->form_validation->set_rules('ch_des3','Choices','required');
$this->form_validation->set_rules('ch_des4','Choices','required');
$this->form_validation->set_rules('ans','Answer','required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if($this->form_validation->run() ){
echo $qtopic_id ;
$data['ques'] = ($this->input->post('ques'));
$data['ch_des1'] = ($this->input->post('ch_des1'));
$data['ch_des2'] = ($this->input->post('ch_des2'));
$data['ch_des3'] = ($this->input->post('ch_des3'));
$data['ch_des4'] = ($this->input->post('ch_des4'));
$data['ans'] = ($this->input->post('ans'));
if($id=$this->queries->registerChoices($data) )
{
$this->session->set_flashdata('message','Test Added Succesfully');
return redirect('admin/testtwo');
}
else {
$this->session->set_flashdata('message','Failed to Add Test');
}
return redirect('admin/testtwo');
}
else {
$this->addQuestion();
}
}
}
model:
----updated---
public function registerChoices($data) {
echo $this->input->post('qtopic_id');
$question_arr = [
'ques' => $data['ques'],
'qtopic_id' => 19
];
$choices_arr = [
'ques' => $data['ques'],
'ch_des1' => $data['ch_des1'],
'ch_des2' => $data['ch_des2'],
'ch_des3' => $data['ch_des3'],
'ch_des4' => $data['ch_des4'],
'ans' => $data['ans']
];
// echo "<pre>";
// var_dump($question_arr);
// var_dump($choices_arr);
// exit;
$this->db->insert('tbl_choices',$choices_arr);
$this->db->insert('tbl_question',$question_arr);
return $this->db->insert_id();
}
error messages that i encountered
Your code for register choices is a bit unclear. insert_id isn't a function that accepts data nor does it do inserting, it simply returns the last inserted id after you perform an insert query. I think what you want is something like:
function registerChoices($data) {
if ($this->db->insert('tablename', $data)) {
return $this->db->insert_id();
}
return false;
}
Usage:
$last_insert_id = $this->somemodel->registerChoices($data);
if ($last_insert_id) {
echo "item with id $last_insert_id was created!";
} else {
show_error('Query failed!');
}

How to use model function result in controller

I have an error in my controller. I am trying to use the result coming from model function to call another function in my model. I am using Codeigniter Framework. hope you can help me out. Thanks
Controller:
function photographer_campaign_details(){
$camp_id = $this->uri->segment(4);
$data['page_title'] = 'Photographer Campaign Details';
$adminId = $this->session->userdata('adminid');
$campaign = $this->Admin_model->get_all_photographer_campaign_details($camp_id);
$data['seller'] = $this->Admin_model->get_seller_name_by_id($campaign['uid']);//error is here: Undefined index: uid
$data['campaign'] = $campaign;
$this->load->view('admin/photographer_campaign_details',$data);
}
My Model:
function get_all_photographer_campaign_details($camp_id) {
$this->db->select('*');
$this->db->where('campaign_id',$camp_id);
$query = $this->db->get('ps_campaigns');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
return $data;
}
return array();
}
//get seller name by id
function get_seller_name_by_id($uid)
{
$this->db->select('firstname, lastname');
$this->db->where('id', $uid);
$query = $this->db->get('ps_users');
//return $query->row();
return $query->result_array();
}
an error is coming from the controller: Undefined index: uid
Looking at your get_all_photographer_campaign_details, if no rows are found then you return an empty array.
In your controller, you never check to see if a valid entry was found. As a result you get your undefined index: uid when an id is referenced in the URL that doesn't correspond to an entry, because $campaign is empty and doesn't have a uid key. Try something like this:
function photographer_campaign_details(){
$camp_id = $this->uri->segment(4);
$data['page_title'] = 'Photographer Campaign Details';
$adminId = $this->session->userdata('adminid');
$campaign = $this->Admin_model->get_all_photographer_campaign_details($camp_id);
if (!$campaign ){
show_404();
}
$data['seller'] = $this->Admin_model->get_seller_name_by_id($campaign['uid']);//error is here: Undefined index: uid
$data['campaign'] = $campaign;
$this->load->view('admin/photographer_campaign_details',$data);
}
Additionally, you are returning data wrong in the event that you do find data. Namely this bit in get_all_photographer_campaign_details:
foreach ($query->result_array() as $row) {
$data[] = $row;
}
Should be something like:
foreach ($query->result_array() as $row) {
$data = $row;
break;
}
The problem is that you are appending the row as one row in $data, but your controller is expecting to get the actual data itself. I.e. your controller is expecting this:
[
'campaignid' => 1,
'uid' => 'ijerjeire'
]
But you are returning this:
[
[
'campaignid' => 1,
'uid' => 'ijerjeire'
]
]
Note the extra array that everything is wrapped around. Basically, your model is returning an array of results, when your controller is just expecting results. My above suggestion will work if there is only ever supposed to be one campaign returned. If that is not the case, then you need to adjust your controller instead of your model method.
To reiterate my other point: make sure and validate the user input that comes from the URL. Otherwise you will return PHP errors instead of 404's.

How can I pass a variable from view to model in mvc (PHP)

I'm working on a similar thing as this one. But I'm trying to assign button either "Join" or "Enter" based on if someone joined the group. The problem is that I'm not sure how I can pass the variable from the category ID ($cats_id) to the view file.
I created a function in the model that checks if the row exists and returns true.
// check if joined the group
public static function checkIfJoined($cats_id)
{
$database = DatabaseFactory::getFactory()->getConnection();
$users_id = Session::get('user_id');
$sql = "SELECT cats_id,users_id FROM categories_joined WHERE users_id = :users_id AND cats_id = :cats_id";
$query = $database->prepare($sql);
$query->execute(array(':users_id' => $users_id, ':cats_id' => $cats_id));
// fetchAll() is the PDO method that gets all result rows
if ($query->rowCount() >= 1 || Session::get('user_account_type') == 7) {
return true;
}
}
Then in Controller I render the model to the view.
public function index()
{
$cats_id = ""; // this doesn't work right obviously
$this->View->render('dashboard/index', array(
'categories' => DashboardModel::getAllCategories(),
'joined' => DashboardModel:: checkIfJoined($cats_id)
));
}
in the view I pass the variable from the preview function 'categories'.
<?php if ($this->categories) { ?>
<?php foreach($this->categories as $key => $value) { ?>
...
<?php $cats_id = $value->cat_id; if ( $this->joined == true ): ?>Enter
<?php else: ?>Join
<?php endif; ?>
You can never pass anything from view to controller because view is parsed after controller.
What you can do here is use model directly by calling DashboardModel::checkIfJoined($cats_id) in your view but that's not perfect approach.
It'll be better to prepare that data in the controller and then pass it to view.
Example controller
public function index()
{
$this->View->render('dashboard/index', array(
'categories' => DashboardModel::getAllCategories(),
'userCategories' => DashboardModel::getUserCategories()
));
}
Example view
<?php
if ($this->categories) {
foreach ($this->categories as $key => $value) {
if (in_array($value->id, $this->userCategories) {
echo 'Joined';
} else {
echo 'Join';
}
}
?>
In this example DashboardModel::getUserCategories() should return results from SELECT cats_id FROM categories_joined WHERE users_id = :users_id.

Codeigniter load query into an array

I have been trying to figure out how to load the data in a query to an array.
$query->row() //only brings back a single row of data when there are more entries in the database.
If I just use a foreach loop and echo in the model code below, The data is simply displayed on the screen. It's not in a variable or an array. It is just text on the screen all jammed together.
I had a really hard time trying to find a code example that would show me how to use the
$this->db->get_where('table' array('column' => $var);
I finally found it but then the example on codeigniters site only echos the query back to the screen.
http://ellislab.com/codeigniter/user-guide/database/results.html
This is not useful for production.
My controller code is:
public function record(){
/*
* Here the id is being passed to the record
* function to retieve the parent and childrens data
*
*/
$getid['id'] = $this->uri->segment(3);
$accld = $getid['id'];
$data = array();
$this->load->model('account');
$account = new Account();
$account->load($getid['id']);
$data['account'] = $account;
$this->load->model('children');
$children = new Children();
$children->accld($getid['id']);
$data['children'] = $children;
$this->load->view('childeditdisplay', $data );
}
}
My Model code is this:
public function accld($id)
{
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$c_data = array();
foreach ($query->result() as $row){
$c_data[] = $row ;
}
return $c_data;
/*
* Note:
* I need to figure out how to load to an array to pass back to the
* controller to pass to the display
* I can echo to the screen the results but that is uncontrolled.
*
*/
}
If I do this:
public function accld($id)
{
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
foreach ($query->result() as $row){
echo $row->id ;
// and all the other fields below here
}
}
My rows are echoed to the screen. But there is no control. So any help in getting control of my data would be greatly appreciated.
ANSWER
This is finally what worked to bring back all the results and not just one row.
/**
* Populate from an array or standard class.
* #param mixed $row
*/
public function populate($row) {
foreach ($row as $key => $value) {
$this->$key = $value;
}
}
public function accld($id) {
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$this->populate($query->result());
}
Just do
$query = $this->db->get_where($this::DB_TABLE, array('accId' => $id));
$_array = $query->result_array();
Do whatever with $_array.

Getting the rowid after adding an item with CI cart?

On the codeigniter website it says the the insert() method will return a $rowid of the latest inserted product. However How exactly do I grab it?
$data = array();
$insert = $this->cart->insert($data);
I tried $insert['rowid'] and $insert->rowid but neither seem to work.
Thank you!
introducing: insert_id()
like this
$id = $this->db->insert_id();
return $id;
in your model, lets call it friend_model
function insertRow()
{
// Prepare data, normally you would pass this in
$data = array(
'first' => 'john',
'last' => 'smith'
);
// insert data
$this->db->insert( 'friends', $data );
// confirm insert
if ( $this->db->affected_rows() == '1' )
// return new ID
{ $id = $this->db->insert_id();
return $id; }
// else did not insert, return false
else {return FALSE;}
}
in your controller, check if you got an id back from model
if(! $id = $this->friend_model->insertRow() )
// it no work
{ // some error method
}
else
{ // success !
}

Categories