Run multiple queries in Codeigniter model - php

I do have a Codeigniter model function to insert data to two tables. I used this kind of setup.
function abc{
{query 1}
{query 2}
return 'success'
}
but sometimes the function returns success without executing the second query. How to prevent it?

The simplest way to do this is:
function abc() {
$result1 = query1_function();
if ($result1) {
$result2 = query2_function();
} else {
return 'fail on query 1';
}
if ($result1 && $result2) {
return 'success';
}
return 'fail on query 2';
}
Of course, your query1_function and query2_function would need to return the $this->db->insert_id() after call to the $this->db->insert() function.

Related

Redirecting not working in codeigniter

So here's what I want to do. I want to check if the userid in segment(3) exist or else it will redirect somewhere instead of still loading the view with an error.
Here's the example url
http://localhost/ems/edit_user/edit_user_main/1001
Now if I try to edit the userid in segment(3) and intentionally put an invalid userid, it still loads the view and i don't know why
Here's my function
public function edit_user_main(){
$id = $this->uri->segment(3);
$check = $this->get_data->check_if_exist($id);
if($check) {
$data['title'] = 'Edit User';
$data['id'] = $this->session->userdata('usertoedit');
$this->load->model('accounts/get_data');
$item = $this->get_data->get_user($id);
$data['user'] = $item[0];
$data['main_content'] = 'edit_user/edit_user_main';
$this->load->view('includes/template', $data);
} else {
redirect('admin/adminuser');
}
}
Here's the model
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query) {
return TRUE;
} else {
return FALSE;
}
}
There is no problem with the fetching of data.
The problem is even if the userid doesn't exist, the view is still loading but with an error coz there's no data for that userID. It's not redirecting,
I tried using print_r and it working fine, the value of the $check is 1 when there's a valid userID.
Hope someone can help me with this. Thank you
With your function it will always return true because the statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always execute,So you need to check query is returning any result row or not with the statement
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
Try this..
With the function it will always return true because the following statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always be execute, So need to check query is returning any result row or not
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
And load heper as:-
$this->load->helper('url');
before the redirection

recursive function in codeigniter returns 500 error

i have this next recursive function that keep return 500 error
public function get_parent($cat=0){
$ci = &get_instance();
$q= $ci->db->query("SELECT category_id,parent_id FROM tbl_products_categories WHERE category_id = {$cat}");
if($q->num_rows()>0){
$row = $q->row();
if($row->parent_id == 0){
return $row->category_id;
break;
}else if($row->parent_id != 0){
$this->get_parent($row->category_id) ;
}
}
else{
return 0;
}
}
i am calling the function like this:
$cat = 9;
$main_cat =$this->get_parent($cat);
$this->get_parent($row->category_id);
is calling get_parent with the same ID you originally called it with so it keep recursing until you get a stack overflow.
FYI Depending on your database, it should be possible to do what you want in pure SQL without multiple queries.
Edit: Also, you probably want to do
$ci->db->query("SELECT category ... WHERE category_id=?", array($cat));
instead of what you have now because your current query is susceptable to SQL injection if your function is called with anything other than a number.

Two different functions one works one calls a non-object

I have two functions getCompanyDetails and getHostingDetails
The first database getCompanyDetails works fine but the getHostingDetails shows
Trying to get property of non-object
getCompanyDetails:
Controller: $data['companyName'] = $this->quote->getCompanyDetails()->companyName;
Model:
public function getCompanyDetails()
{
$this->db->select('companyName,companySlogan,companyContact,
companyEmail,companyWebsite,companyPhone,
companyFax,companyAddress');
$this->db->from('companyDetails');
$result = $this->db->get();
if($result->num_rows()<1)
{
return FALSE;
}else{
return $result->row();
}
}
getHostingDetails:
Controller:
$data['hostingRequired'] = $this->quote->getHostingDetails()->hostingRequired;
Model:
public function getHostingDetails()
{
$this->db->select('hostingRequired,domainRequired,domainToBeReged,
domaintoBeReged0,domainTransfer,domainToBeTransfered,
domainToBeTransfered0,currentHosting');
$this->db->from('hostingDetails');
$result = $this->db->get();
if($result->num_rows()<1)
{
return FALSE;
}else{
return $result->row();
}
}
Well, one method returns an object from $result->row() and the other false. You can't call a method on false.
false is returned when no record is found. So you need to check the return value before using it.
Well in your get functions chances is your code might return you false if there is no rows returned. You might want to check before retrieving the details. Example:
$details = $this->quote->getHostingDetails();
if($details){
$data['hostingRequired'] = $details->hostingRequired;
}
The problem is probably how you use those functions in your controller. If any of them returns FALSE, then
$this->quote->getHostingDetails()->hostingRequired;
is going to give you errors. Try
if ($row = $this->quote->getHostingDetails()) {
echo $row->hostingRequired;
}

where to return value from a recursive function in php

I'm using recursive function to get values out of database, but in my code I get only first record as return. Where should I put return to return function after everything completes?
function sidebar_sub_sub($id)
{
$sql="select subcatagory_id,subcatagory_name,haschild,parent from subcatagory where parent=".$id."";
$query=mysql_query($sql);
$resultset=array();
if(mysql_num_rows($query))
{
while($result=mysql_fetch_assoc($query))
{
array_push($resultset,$result);
if($result['haschild'])
{
$sb=sidebar_sub_sub($result['subcatagory_id']);
}
}
}
return $resultset;
}
you store the result of sidebar_sub_sub() in $sb. But then you do nothing with this variable.
You could do a array_push($resultset, sidebar_sub_sub()) instead. This way you return the whole stack of the recursion.
Try the below script that i used for my categories table in which there are just three fields id, name and parent_id. It may work for you.
$resultset=array();
function sidebar_sub_sub($id)
{
global $resultset;
$sql="select id,name,parent_id from categories where parent_id=".$id."";
$query=mysql_query($sql);
if(mysql_num_rows($query))
{
while($result=mysql_fetch_assoc($query))
{
array_push($resultset,$result);
if($result['parent_id']>0){
sidebar_sub_sub($result['id']);
}
}
}
return $resultset;
}
$result = sidebar_sub_sub(1);

Form Validation w/ sql + codeigniter

I'm working on creating a callback function in codeigniter to see if a certain record exists in the database, and if it does it'd like it to return a failure.
In the controller the relevent code is:
function firstname_check($str)
{
if($this->home_model->find_username($str)) return false;
true;
}
Then in the model I check the database using the find_username() function.
function find_username($str)
{
if($this->db->get_where('MasterDB', array('firstname' => $str)))
{
return TRUE;
}
return FALSE;
}
I've used the firstname_check function in testing and it works. I did something like
function firstname_check($str)
{
if($str == 'test') return false;
true;
}
And in that case it worked. Not really sure why my model function isn't doing what it should. And guidance would be appreciated.
if($this->home_model->find_username($str)) return false;
true;
Given that code snippet above, you are not returning it true. If that is your code and not a typo it should be:
if($this->home_model->find_username($str)) return false;
return true;
That should fix it, giving that you did not have a typo.
EDIT:
You could also just do this since the function returns true/false there is no need for the if statement:
function firstname_check($str)
{
return $this->home_model->find_username($str);
}
So the solution involved taking the query statement out of if statement, placing it into a var then counting the rows and if the rows was > 0, invalidate.
Although this is a more convoluted than I'd like.
I find your naming kind of confusing. Your model function is called 'find_username' but it searches for a first name. Your table name is called 'MasterDB'. This sounds more like a database name. Shouldn't it be called 'users' or something similar? I'd write it like this :
Model function :
function user_exists_with_firstname($firstname)
{
$sql = 'select count(*) as user_count
from users
where firstname=?';
$result = $this->db->query($sql, array($firstname))->result();
return ((int) $result->user_count) > 0;
}
Validation callback function :
function firstname_check($firstname)
{
return !$this->user_model->user_exists_with_firstname($firstname);
}

Categories