how to combine query() and limit() methods in CodeIgniter - php

Is it possible to do something like this in codeigniter:
publi function getcat($category_id)
{
$query = "(SELECT cat.id, cat.title ";
$query = $query . "FROM bf_categories cat ";
$query = $query . "WHERE cat.id=" . $category_id;
$this->db->limit(2, 4);
$records = $this->db->query($query);
return $records->result();
}
I've simplified the query just for demo purposes... but it's actually quite complex, which is why I've decided to use the query() method.
But the limit clause is not being included in the query... I've verified by enabling the codeigniter profiler in my controller and I can see that the query is run with out any limit clause.
Can you tell me how I can accomplish this using the query() method?
Edit 1
I've modified my model to look like this:
public function get_categories_and_products($limit=5, $offset=0, $category_id=null)
{
print "<BR>the function got the following offeset: $offset and limit: $limit";
$query = "(SELECT cat.category_id, cat.title, cat.image_thumb, cat.deleted, cat.display_weight ";
$query = $query."FROM bf_categories cat ";
$query = $query."WHERE cat.parent_id=".$category_id;
$query = $query." AND cat.category_id <>".$category_id;
$query = $query.") UNION (";
$query = $query."SELECT p.product_id, p.name, p.image_thumb, p.deleted , p.display_weight";
$query = $query." FROM bf_product p ";
$query = $query."Inner join bf_product_category cp ";
$query = $query."on p.product_id=cp.product_id ";
$query = $query."Where cp.category_id=".$category_id.") ?";
$records = $this->db->query($query,array($this->db->limit(2, 4)));
return $records->result();
}
I've hardcoded the limit values for now... but ultimately, i'll be using the values that get passed into the method. Unfortunately, this code still does not work.
According to the profiler, here's what's being executed:
(SELECT cat.category_id, cat.title, cat.image_thumb, cat.deleted, cat.display_weight FROM bf_categories cat WHERE cat.parent_id=3 AND cat.category_id <>3) UNION (SELECT p.product_id, p.name, p.image_thumb, p.deleted , p.display_weight FROM bf_product p Inner join bf_product_category cp on p.product_id=cp.product_id Where cp.category_id=3)
SELECT * FROM (`bf_categories`) WHERE `category_id` = '3' LIMIT 4, 2
So it's creating two separate select statements.

I tried this way, multiple join with start and limit. you remove join as per choice.
$this->db->select('*');
$this->db->from('tbl_requestservice as r');
$this->db->join('tbl_service as s','s.service_id=r.service_id');
$this->db->limit($limit, $start);
$query = $this->db->get();
print_r($query->result());
return $query->result();

This is how a query looks like in CI:
$this->db->select("id, title");
$this->db->where("id", $category_id);
$this->db->from("bf_categories");
$this->db->limit($limit);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
echo $row->title;
}
}
If you include the full query, it would be easier to solve the problem or show you a better and more efficient approach.

In the end, I'm doing everything manually.
public function get_categories_and_products($limit=10, $offset=0, $category_id=null)
{
$query = "(SELECT cat.category_id, cat.title, cat.image_thumb, cat.deleted, cat.display_weight ";
$query = $query."FROM bf_categories cat ";
$query = $query."WHERE cat.parent_id=".$category_id;
$query = $query." AND cat.category_id <>".$category_id;
$query = $query.") UNION (";
$query = $query."SELECT p.product_id, p.name, p.image_thumb, p.deleted , p.display_weight";
$query = $query." FROM bf_product p ";
$query = $query."Inner join bf_product_category cp ";
$query = $query."on p.product_id=cp.product_id ";
$query = $query."Where cp.category_id=".$category_id.") limit ".$offset.','.$limit;
$catsandprods= $this->db->query($query);
return $catsandprods->result();
}

http://code-igniter.ru/user_guide/database/active_record.html
$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();
$this->db->get('tablename');
SELECT field1 FROM (tablename)
$this->db->select('field2');
$this->db->limit(10);
$this->db->get('tablename');
// SELECT field1, field2 FROM (tablename) limit 10
$this->db->flush_cache();
$this->db->select('field2');
$this->db->get('tablename');
// SELECT field2 FROM (tablename)

you can use
$query = "(SELECT cat.id, cat.title ";
$query = $query."FROM bf_categories cat ";
$query = $query."WHERE cat.id=".$category_id." ?";
$this->db->query($query,array($this->db->limit(2, 4)));
or
$this->db->select('id,title')->from('bf_categories ')->where('id', $id)->limit(2, 4);
link to doc

Related

I can't figure out how to function selected categories using $where in SQL

I want to show the selected query from the table
<?php
$where = "";
if(isset($_GET['category']))
{
$catid = $_GET['category'];
$where = " WHERE product.categoryid = $catid";
}
Thus is the $where function to get the category
$sql = "SELECT category.*,
category.category_id , items.id AS itemID,items.asset_tag,items.name,
items.brand,items.status,
items.quantity,items.category_id,
items.color,items.texture,items.photo,items.date,
items.fetch_item FROM items LEFT JOIN category ON
category.category_id=items.category_id
WHERE items.status = 'Available' AND items.fetch_item = '0' $where";
?>
Looks like you did small mistake, because in your "default" query you have already WHERE statement, so in the if you should use AND or OR instead of WHERE again:
$where = "";
if(isset($_GET['category']))
{
$catid=$_GET['category'];
$where = " AND product.categoryid = $catid";
}
additionally you could make your injection of additional WHERE condition a bit more elegant by using sprintf() function. Take a look on example:
$additional_condition = 'AND active=1'
$statement = 'SELECT * FROM users WHERE condition=1 %s';
echo sprintf($statement, $additional_condition);
// Output: SELECT * FROM users WHERE condition=1 AND active=1

How to merge multiple function in single query?

I am trying to combine 3-4 functions inside one function and call this inside another function. for example
public function todayordercount(){
$sql = "SELECT *,count(id) FROM `tbl_order` WHERE DATE(`date_added`) = CURDATE() and status='Delivered'";
$query = $this->db->query($sql);
if($query->num_rows()>0){
return $query->result_array();
}else{
return $query->row_array();
}
}
public function currentmonthcount(){
$sql = "SELECT sum(amount) as amt,sum(shipping) as shiping,sum(commission) as commission,sum(base_price) as base_price,sum(tax_amt) as tax,SUM(LENGTH(product_id) - LENGTH(REPLACE(product_id, ',', '')) + 1) as unit , count(id) FROM `tbl_order` WHERE MONTH(CURDATE())=MONTH(date_added) and status='Delivered'";
$query = $this->db->query($sql);
if($query->num_rows()>0){
return $query->result_array();
}else{
return $query->row_array();
}
}
public function mergeordercount(){
$query1 = $this->db->query("SELECT *,count(id) as today_order FROM `tbl_order` WHERE DATE(`date_added`) = CURDATE() and status='Delivered'");
$query2 = $this->db->query("SELECT sum(amount) as amt,sum(shipping) as shiping,sum(commission) as commission,sum(base_price) as base_price,sum(tax_amt) as tax,SUM(LENGTH(product_id) - LENGTH(REPLACE(product_id, ',', '')) + 1) as unit , count(id) FROM `tbl_order` WHERE MONTH(CURDATE())=MONTH(date_added) and status='Delivered'");
$query3 = $this->db->query("SELECT count(status) as status FROM `tbl_order` WHERE MONTH(CURDATE())=MONTH(date_added) and status='Return'");
$query4 = $this->db->query("SELECT count(response) as calls FROM `tbl_order` WHERE response='pending' or response='hold'");
$query5 = $this->db->query("SELECT count(id) as product FROM `tbl_product`");
$result1 = $query1->row_array();
$result2 = $query2->row_array();
$result3 = $query3->row_array();
$result4 = $query4->row_array();
$result5 = $query5->row_array();
return array_merge($result1, $result2, $result3, $result4, $result5);
}
you should do look like above code it will help you bettor.
Thank You...

MySQL & PHP CMS project 'JOINS'

i have a project to build a CMS. We were giving a few functions.. on is below. I would like someone to explain to me what the 'p', 'ca', and 'cm' mean/stand for?
function getAllPosts() {
global $db;
$sql = "SELECT p.*, ca.catName, COUNT(commentID) as numComments
FROM posts p
LEFT JOIN categorys ca USING (categoryID)
LEFT JOIN comments cm USING (postID)
";
if ($_GET['catID'] != ''){
$catID = (int)$_GET['catID'];
$sql .= "WHERE categoryID = $catID ";
}
$sql .= "GROUP BY postID
ORDER BY postDate DESC";
$qry = mysqli_query($db, $sql);
$result = array();
while ($row = mysqli_fetch_assoc($qry)) {
$result[] = $row;
}
if (count($result) > 0) {
return $result;
}
return false;
}
They are a shorter way to write a query without using the whole table names. (table alias)
E.g. SELECT a.name, a.surname FROM very_long_name_of_my_table [AS] a
instead of
SELECT very_long_name_of_my_table.name, very_long_name_of_my_table.surname FROM very_long_name_of_my_table
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
for more visit: http://www.w3schools.com/sql/sql_alias.asp

Step by step MySql query to PDO

I'm trying to figure out how can I build a query in PDO like this one
//...
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = '1'";
if($this->is($_GET, 'category')) {
$sql['category'] = "AND `category` = '".$_GET['category']."'";
}
if($this->is($_GET, 'tags')) {
$sql['tags'] = "AND `tags` LIKE '%".$_GET['tags']."%'";
}
$sql[] = "ORDER BY `id` DESC LIMIT ".$offset.", ".$rows_per_page;
$query = $this->query(implode(" ", $sql));
//...
I tried something like that..
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = :completed";
if($this->is($_GET, 'category')) {
$sql['category'] = "AND `category` = :category";
}
$sql[] = "LIMIT 0, 5";
$this->db->query(implode(" ", $sql));
$this->db->bind(array(
':completed' => 1,
':category' => $this->is($_GET, 'category')
));
$fetch = $this->db->fetchAll();
print_r($fetch);
but there's a error that says I can not bind nonexistent variables "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"
...and with some research I figure out I can not bind before query
..so.. do you have any idea how can I do this?

Sort the results of a query using results of another query

Im working on a message board of some sort and i have everything up an running except one little part, the threads need to be sorted by the date/time of the latest post in them (standard forum format), which im having lots of trouble wrapping my head around.
This is the querys im using, i know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
$sql = "SELECT Thread_ID, Thread_Title, Board_ID, Author FROM threads WHERE Board_ID='$Board_ID' LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$getauthor = mysql_query("SELECT * FROM members WHERE Member_ID='$Author'");
while ($row = mysql_fetch_assoc($getauthor))
{
$Post_Author = $row['Post_As']; }
$postcount = mysql_query("SELECT Post_ID FROM posts WHERE Thread_ID='$Thread_ID'");
$Posts = mysql_num_rows($postcount);
$getlatest = mysql_query("SELECT * FROM posts WHERE Thread_ID='$Thread_ID' ORDER by Post_DateTime DESC LIMIT 1");
while ($row = mysql_fetch_assoc($getlatest))
{
$Post_DateTime = time_ago($row['Post_DateTime']);
$Member_ID = $row['Member_ID']; }
$getmember = mysql_query("SELECT * FROM members WHERE Member_ID='$Member_ID'");
while ($row = mysql_fetch_assoc($getmember))
{
$Post_As = $row['Post_As']; }
So what im trying to do is Sort $sql by $getlatest, i tried adding another query above $sql that did basically the same as $getlatest and then had $sql order by that but alas it just broke everything.
I know i have to make a variable to sort the $sql by but its that variable thats driving me mad.
any help would be appreciated, thanks.
current error message as requested:
Fatal error: SQL - Unknown column 'posts2.LatestPost' in 'on clause' - SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs FROM threads INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1 ON threads.Thread_ID = Sub1.Thread_ID INNER JOIN members ON threads.Author = members.Member_ID INNER JOIN posts posts2 ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.LatestPost INNER JOIN members members2 ON members2.Member_ID = posts2.Member_ID WHERE threads.Board_ID='1' ORDER BY Sub1.LatestPost DESC LIMIT 0, 25 in C:\wamp\www\forum\include\threads.php on line 86
You should be able to do it using something like this for your first query:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, MAX(posts.Post_DateTime) AS LatestPost
FROM threads
LEFT OUTER JOIN posts ON threads.Thread_ID = posts.Thread_ID
WHERE threads.Board_ID='$Board_ID'
GROUP BY SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author
ORDER BY LatestPost DESC
LIMIT $offset, $rowsperpage";
EDIT
Not tested the following but looking at your selects I think you could probably put it together into a single SELECT. Something like this:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs
FROM threads
INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1
ON threads.Thread_ID = Sub1.Thread_ID
INNER JOIN members
ON threads.Author = members.Member_ID
INNER JOIN posts posts2
ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.Post_DateTime = Sub1.LatestPost
INNER JOIN members members2
ON members2.Member_ID = posts2.Member_ID
WHERE threads.Board_ID='$Board_ID'
ORDER BY Sub1.LatestPost DESC
LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$Post_Author = $row['Post_As'];
$Posts = $row['PostCount'];
$Post_DateTime = time_ago($row['LatestPost']);
$Member_ID = $row['LastPostMemberID'];
$Post_As = $row['LastPostMemberPostAs'];

Categories