modify and redo last query in codeigniter - php

Can I get last query made with active record class and modify some parts of it and redo that query in codeigniter. I am trying to get total pages for my pagination. I can't directly write my query because it is dynamically created on runtime within some for loops and if statements depending on the form submitted to the page.

Do you run your query twice because of the total pages? If yes, check SQL_CALC_FOUND_ROWS and FOUND_ROWS() in SQL.
$this->db->select("SQL_CALC_FOUND_ROwS id",false);
$this->db->any_AR_function(....);
$this->db->limit(...);
$result = $this->db->get();
After this you can call this:
$this->db->select("FOUND_ROWS() as count",false);
$count = $this->db->get();
I hope this is what you want.

You can get last query using:
$last_query = $this->db->last_query();
You can modify this query and then do:
$query = $this->db->query($modified_query);
foreach($query->result() as $row)
{
}

Related

How to declare multiple where condition for a table

hi guy's i have a question.
how to declare a multiple where clause condition inside one php only.
i have try to make my project has a minimum of a php file. i want to make my where clause inside one php file only.
this is the problem i mean. i want to put my code into one php file or inside one <?php ?>. the php code like this
<?php
include("../../Connections/koneksi.php");
$date1= $_POST['date1'];
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='Silo 1'";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
on the code above the query has select table termocouple and the filter of where condition is tanggal and silo. now the problem is i have 12 php file like that. and the different of every php is from the selecting silo, i put Silo 1,Silo 2,Silo 3, ....Silo 12.
please someone help me with this. i want to make it simple in one php file. im really appreciated when you give me an example
In order to minimize your code, if you are using the same query or code more than one time in the same project, it is more recommended to create a function, that you will call anytime you need to execute the code.
So here, since you are using the same query 12 times, you will have to create a function that executes this query, and then call this function every time you want to execute the query.
The function takes parameters, so you will have to give the function the database connection parameter $db in order to connect to the database since you are using this connection inside the function, and then you have to add the values of the where clause to the parameters also.
So your function here will take the database connection $db, $date1 fetched from $_POST, and $silo fetched from $_POST
At the end of the function, you can return any value you wish to return, so in your case, you will have to return the $rows array fetched from the query
Create a common php fileand create a function in it.
Lets say the file name is libraries.php
in this file write the following code:
<?php
function getRows($db, $date, $silo) {
$sql = "SELECT * FROM termocouple where tanggal='$date' AND silo='$silo'";
$query = mysqli_query($db, $sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
return json_encode($rows);
}
?>
And in each of the files where you are calling the query you will remove the php code and replace it with the following:
<?php
include("../../Connections/koneksi.php");
include("{path-to-file}/libraries.php");
$date1= $_POST['date1'];
$silo = $_POST['silo'];
$rows = getRows($db, $date1, $silo) ;
?>
I am assuming these 12 PHPs are called in diff scenarios. Why dont you pass some param from client side so that the PHP knows which scenario to execute.
$date1= $_POST['date1'];
$silo= $_POST['silo'];//This could be 'Silo 1 OR 'Silo 2' etc.
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='$silo'";
$query = mysqli_query($db,$sql);

Yii-How to write this query in yii?

I am trying to fetch the no of records, but I am unable to write this query in yii. My sql query is given below.
select count(review) from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01')) . I am currently writing this query in yii is given below.
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created'>=DATE_FORMAT(NOW() ,'%Y-11-01'))
->queryAll();
But I am getting this error Fatal error: Call to undefined function NOW() in G:\www\ba.dev\protected\views\business\stats.php on line 19. I am sure it is because of my poor yii query. Kindly correct my query.
If you are willing to run the entire query and not use the active record pattern You can try built-in YII commands to do that.
$query = 'select * from post where category=:category';
$list= Yii::app()->db->createCommand($query)->bindValue('category',$category)->queryAll();
Explanation: $query should be obvious and =:category is binding the variable category dynamically to the query for security reasons. In next line I am creating the query and substituting the value of category variable by using bindValue() function, finally queryAll retrieves all the records in the database. Hope it is clear now.
In your case
$query = "select count(review) as result from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01'))" ;
$list= Yii::app()->db->createCommand($query)->queryAll();
Now you can access the result like this:
foreach ($rows as $row) {
$result = $row["result"];
}
Try this,
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created >=DATE_FORMAT(NOW() ,"%Y-11-01")')
->queryScalar();

CodeIgniter Select Statement with Where clause

Hi I'm new to CodeIgniter and I just want to know How will I query from my MySql Db, a Select Statement with a where clause, I know it can be searched from the net but whenever I try something I get errors, It's really frustrating. The string in the Where clause will be coming from a User Input. Thanks guys!
You can do as Mehedi-PSTU stated, however it seems as though you're a little new to this, so here's some extra information:
I'll copy Mehedi-PSTU for the most part here.
$this->get->where('column_name', $equals_this_variable);
$query = $this->db->get('table_name');
This will store the query object in the variable $query.
if you wanted to convert that to a usable array, you just perform to following.
$results = $query->result_array();
Or you can loop through it like this:
foreach($query->result_array() as $result){
// Perform some task here.
}
A better or even full understanding can probably come from:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
Try something like this
$this->db->where('db_attr', $var);
return $this->db->get('table');
Try this one.
$id = 'your id';
$this->db->select("*");
$this->db->from("table_name");
$this->db->where('id','$id');
$query = $this->db->get();
return $query->result_array();
In Codeigniter with Method Chaining Style :-
$data['getData'] = $this->db->get_where('table_name',array('column_name'=>$var))->result_array();

Count rows before adding a further limit statement CodeIgniter?

I have ran into a problem...
I have a bunch of where statments like so...
$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
Then a limit statement
$this->db->limit($limit, $offset);
And finally my get statement
$query = $this->db->get('table-name');
My problem is I need to count the results before my limit statement, to get the total rows without the limit.. So I tried this..
$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
$num_rows = $this->db->count_all_results();
$this->db->limit($limit, $offset);
$query = $this->db->get('table-name');
This counts my rows with the where statements fine.. However, the get statement now gets records without the previous where statements working.
It's not visible, but there is a large amount of code handling more where statements, and grabbing things in urls, So I'd prefer not to perform the retrieval of data twice in order to fix this...
Cheers!
I know this is an old question, but I just ran into this problem and came up with a different solution.
The idea is to take a copy of the db class before the limit and offset.
$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
//here we use the clone command to create a shallow copy of the object
$tempdb = clone $this->db;
//now we run the count method on this copy
$num_rows = $tempdb->from('table-name')->count_all_results();
$this->db->limit($limit, $offset);
$query = $this->db->get('table-name');
I know that's an old question but I found a pretty simple solution.
//do your select, from and where
$this->db->select('your selects');
$this->db->from('your table');
$this->db->where('your where');
//get the filtered rows count
//the trick is the first empty parameter and second false parameter
$filtered_count = $this->db->count_all_results('', false);
//limit your results and get the rows
$this->db->limit($length, $start);
$results = $this->db->get()->result_array();
Hope it helps someone
$get_data = $this->your_model->get_data();
$data = $get_data['data'];
$count = $get_data['count'];
Model
function get_data($limit = 10, $offset= 0)
{
$table = 'table-name';
$where = array('Pool' => 1, 'Beedrooms >=' 3);
$return['data'] = $this->db->from($table)->where($where)->limit($limit, $offset)->get();
$return['count'] = $this->db->from($table)->where($where)->count_all_results();
return $return;
}
$this->db->select('*');
$this->db->from('users');
$this->db->where('active',$status);
//open1 here we copy $this->db in to tempdb and apply
//count_all_results() function on to this tempdb
$tempdb = clone $this->db;
$num_results= $tempdb->count_all_results();
// now applying limit and will get actual result
$this->db->limit(10);
$this->db->get();
$query = $this->db->last_query();
$res = $this->db->query($query);
$data_array = array('num_results' => $num_results, 'results' => $res->result() );
return $data_array;
It is quite evident that you would need to use two different queries. It would be optimum to do this as quickly as possible using a single query, but since you need to get all the records before the second query, we need to use two queries.
However, you can optimize the first query based on the engine you use with MySQL. If you use InnoDB then you should use SELECT COUNT(*) FROM <table-name> cause the total row size is cached in InnoDB.
I believe count_all_rows uses count(*) for performance and you should be sorted using this direcctly.
With MyISAM you can use COUNT(<column-name>).
So, you have a count function in your model class which returns the count for your table and then you can call the function to insert/update/get data from your database.
You can use SQL_CALC_FOUND_ROWS of mysql
SELECT SQL_CALC_FOUND_ROWS * FROM table1
WHERE
cond1, cond2, ..., condN
LIMIT 10
SELECT FOUND_ROWS();
This is using mysql, you may need to check how to use it codeignitor way.
Reference:
https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_found-rows
I know this question is old but I had the same issue and got a simpler solution than the displayed here. No need to build the query twice and no need to clone the db class. Just count the result without resting the query builder after you add the where part and then you add the limit and execute your query.
$this->db->where('Pool', 1);
$this->db->where('Beedrooms >=' 3);
$count = $this->db->count_all_results('table-name', false); // No reset query builder
$this->db->limit($limit, $offset)
$result = $this->db->get();
You are going to have two variables:
$count with the number of results and $result with the result.

Codeigniter return result and row

In the Model class I use return $query->row(); to return single rows and return $query->result(); when returning multiple rows.
On a single page I have to return single rows and multiple rows from 2 separate tables.
Table users contains general information like the user name, full name, and email address.
Table user_links contains links submitted by the respective user and has multiple rows for each user.
My query
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_links', "user_links.user_id = users.user_id");
$this->db->where('users.user_id', $user_id);
$this->db->where('user_links.user_id', $user_id);
$query = $this->db->get();
return $query->row();
In my controller I load the query in my view by
$data['row'] = $this->User_model->user_read($user_id);,
$user_id being the 3rd URL segment containing the unique user id.
Finally, in my view I retrieve rows by echo $row->first_name;
This works for single rows but how can I create a foreach loop for user links? The goal is to avoid loops for single rows and use them just for retrieving multiple rows.
This is psuedo code but you can probobly do something like this
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_links', "user_links.user_id = users.user_id");
$this->db->where('users.user_id', $user_id);
$this->db->where('user_links.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->row();
}
elseif ($query->num_rows() > 1)
{
return $query->result_array(); //This returns an array of results which you can whatever you need with it
}
else
{
//Add some logic to handle if there are zero results
}
If I understand your question correctly, you want to get both the user data as well as user_links data with a single query while avoiding iterating through it to get the user's data. While this may be possible using result_array, I would advise against it since you will get 0 results when there are no entries in user_links for that particular user.
My suggestion is that you use two queries, one to get the user from the user table, another to get user's links from user_links table. This will also help you avoid joins.
Hard to tell what you want.
You want a function that checks if you're passing a row() or a result() and treat them accordingly.
In my opinion your code would be easier to read (and maintain) if you just passed everything as a result(). And do check if the set is empty to show a nice message to the user.
Sounds like you're looking for some of the other features already provided by CI's Active Record: http://codeigniter.com/user_guide/database/results.html
For what you are doing it sounds like using the built in function result_array would work. You use it like so:
TAKEN FROM LINK ABOVE
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
You can just replace this line:
$this->db->join('user_links', "user_links.user_id = users.user_id");
With this one:
$this->db->join('user_links', "user_links.user_id = users.user_id", 'left outer');
Join in codeigniter uses INNER JOIN by default but in some cases if there is no data in user_links it returns nothing so u can use LEFT JOIN in your frame work CI it used like i mentioned above.

Categories