Does anyone can help me,I have mysql query and i have test it in phpmyadmin:
select items.name, items.category, items.supplier_id, items.item_number,
items.product_id, items.description, items.size, items.tax_included,
items.cost_price, if(items_tier_prices.unit_price is not null,
items_tier_prices.unit_price,items.unit_price) as unit_price,
items.promo_price, items.start_date, items.end_date, items.reorder_level,
items.item_id, items.allow_alt_description, items.is_serialized,
items.image_id, items.override_default_tax, items.is_service, items.deleted
from items, item_kit_items_formula
left join items_tier_prices
on items_tier_prices.item_id=item_kit_items_formula.item_id
left join price_tiers
on price_tiers.id=items_tier_prices.tier_id
where item_kit_items_formula.item_id=items.item_id
and item_kit_items_formula.item_kit_id=1
and (price_tiers.name is null or price_tiers.name like '%Jendela Kaca Mati Single%')
Query above display results just like i want. But when i put into a model function (that just work before with simple query), program dont works.
function get_info3($item_id)
{
$this->db->select('items.name, items.category, items.supplier_id, items.item_number, items.product_id, items.description, items.size, items.tax_included, items.cost_price, if(items_tier_prices.unit_price is not null, items_tier_prices.unit_price,items.unit_price) as unit_price, items.promo_price, items.start_date, items.end_date, items.reorder_level, items.item_id, items.allow_alt_description, items.is_serialized, items.image_id, items.override_default_tax, items.is_service, items.deleted ');
$this->db->from('items, item_kit_items_formula');
$this->db->join('items_tier_prices','items_tier_prices.item_id=item_kit_items_formula.item_id','left');
$this->db->join('price_tiers','price_tiers.id=items_tier_prices.tier_id','left');
$this->db->where('item_kit_items_formula.item_id=items.item_id');
$this->db->where('item_id',$item_id);
$this->db->where('(price_tiers.name IS NULL or price_tiers.name like "%jendela kaca mati single%"');
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
$item_obj=new stdClass();
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}
my previous code that work is:
function get_info($item_id)
{
$this->db->from('items');
$this->db->where('item_id',$item_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$item_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}
Can anyone help me to look at this CI function? what i have done wrong?
Thanks you guys!
function get_info3($item_id)
{
$this->db->select('i.*,i_t_p.*,i_k_i_f.*,pt.*,if(i_t_p.unit_price is not null, i_t_p.unit_price,i.unit_price) as unit_price');
$this->db->from('items as i');
$this->db->join('items_tier_prices as i_t_p','i_t_p.item_id=i_k_i_f.item_id','left');
$this->db->join('price_tiers as pt','pt.id=i_t_p.tier_id','left');
$this->db->where('i_k_i_f.item_id=i.item_id');
$this->db->where('i.item_id',$item_id);
$this->db->where('(pt.name IS NULL or pt.name like "%jendela kaca mati single%"');
}
you have to join table , i try to reduce your code but i don't know this item_kit_items_formula table is where to join with which id so you have to join this too ..hope this would help ..
I edited in my code,
try this:
function get_info3($item_id)
{
$sql_query = "select items.name, items.category, items.supplier_id, items.item_number,
items.product_id, items.description, items.size, items.tax_included,
items.cost_price, if(items_tier_prices.unit_price is not null,
items_tier_prices.unit_price,items.unit_price) as unit_price,
items.promo_price, items.start_date, items.end_date, items.reorder_level,
items.item_id, items.allow_alt_description, items.is_serialized,
items.image_id, items.override_default_tax, items.is_service, items.deleted
from items, item_kit_items_formula
left join items_tier_prices
on items_tier_prices.item_id=item_kit_items_formula.item_id
left join price_tiers
on price_tiers.id=items_tier_prices.tier_id
where item_kit_items_formula.item_id=items.item_id
and item_kit_items_formula.item_kit_id=1
and (price_tiers.name is null or price_tiers.name like '%Jendela Kaca Mati Single%')";
$query = $this->db->query($sql_query);
if($query->num_rows()==1)
{
return $query->row();
}
else
{
$item_obj=new stdClass();
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$item_obj->$field='';
}
return $item_obj;
}
}
Related
I want codeigniter search to be match with any one word to column.
Example: Let's Say Search Query is "Fashion Outlet for Mens", Now in table column title is "Fashion Outlet" only so i want search input to be split word by word and match column.
Any Help Please
public function search($query)
{
$q = $this->db->from('tablename')
->like('title',$query)
->get();
return $q->result();
}
Updated Question
public function search_query($query,$limit,$offset)
{
$keywords = explode(' ', $query);
foreach ($keywords as $keyword)
{
$keyword = trim($keyword);
$this->db->or_where("`title` LIKE '%$keyword%'");
$this->db->join('table2', 'tablename.id = table2.id');
$this->db->limit( $limit , $offset );
$this->db->order_by('updated_on','desc');
}
$this->db->get('tablename');
return $this->db->result();
}
Error Got
Not unique table/alias: 'table2'
SELECT * FROM `tablename` JOIN `table2` ON `tablename`.`id` = `table2`.`id` JOIN `table2` ON `tablename`.`id` = `table2`.`id` WHERE `title` LIKE '%fashion%' OR `title` LIKE '%outlet%' ORDER BY `updated_on` DESC, `updated_on` DESC LIMIT 50
Please find the Updated Answer for Order By Keyword Priority.
$keywords = explode(' ', $query);
$this->db->select('*');
$this->db->from('tablename');
$this->db->join('table2', 'tablename.id = table2.id','left');
$orderbyQry = "CASE ";
foreach ($keywords as $key => $keyword)
{
$orderbyQry.="WHEN tablename.title LIKE '%$keyword%' THEN $key ";
$keyword = trim($keyword);
$this->db->or_where("tablename.title LIKE '%$keyword%'");
}
$orderbyQry.=" ELSE 100 END ";
$this->db->limit( $limit , $offset );
$this->db->order_by($orderbyQry,'asc');
$this->db->get();
return $this->db->result();
Please join the table only once, and put the limit and order_by clause out of the loop.
public function search_query($query, $limit, $offset) {
$keywords = explode(' ', $query);
$this->db->select('*');
$this->db->join('table2', 'tablename.id = table2.id');
foreach ($keywords as $keyword)
{
$keyword = trim($keyword);
$this->db->or_where("`title` LIKE '%$keyword%'");
}
$this->db->limit( $limit , $offset );
$this->db->order_by('updated_on','desc');
$this->db->get('tablename');
return $this->db->result();
}
Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
into Codeigniter query just like the image below for example
When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
But if you insist on using Query Builder I believe this your answer
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
You can do
public function view_customers()
{
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";
return $this->db->query($sql)->result();
}
You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
$this->load->model('My_Model');
$data = new stdclass;
$data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}
Model:
public function view_users($param = null) //no value passed
{
$condition = '1';
if (!empty($param)) { //Having this will trap if you input an array or not
foreach ($param as $key=>$val) {
$condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
}
}
$sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
// Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";
return $this->db->query($sql)->result();
}
I'm trying to do a filter search functionality in codeigniter. I have a table named products and my system has the functionality to filter these products by category and by date. I have a mysql code in mind which looks something like this:
SELECT * from products WHERE product_category='Cloth'
INTERSECT
SELECT * from products WHERE ('insert date logic here')
So it should return records (via id) from the same table named products. However, there's no INTERSECT in mysql so I don't know how to do this. Any help would be greatly appreciated!
This is my code just for the part of the product category
$this->db->limit($limit,$start);
$query = $this->db->query('SELECT * from product_advertised WHERE quantity > 0 AND prodcatid='.$prodcats[0].' LIMIT '.$start.','.$limit);
if(sizeof($prodcats > 1)) {
$query_str = "SELECT * FROM product_advertised WHERE quantity>0 AND ";
$str="";
for($i = 0;$i < sizeof($prodcats);$i++) {
if($i != sizeof($prodcats)-1) {
$str = $str. "prodcatid=".$prodcats[$i]." OR ";
}
else {
$str = $str. "prodcatid=".$prodcats[$i]." LIMIT ".$start.",".$limit;
}
}
$query_str .= $str;
$query = $this->db->query($query_str);
}
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
Why wouldn't you just use and?
SELECT *
from products
WHERE product_category = 'Cloth' AND
('insert date logic here');
I have a problem whereby I am running a SELECT query that returns a valid result set. I process the results using mysqli_fetch_assoc and then pass the result set to mysqli_free_result, which returns false. I have done a var_dump of the result before and after the call to confirm it is a valid result (seems to be to me - I can access the data I expect to). The query I am running is something like:
select us.user_session_key
, u.user_key
, ut.code as user_type
from t_user u
inner join t_user_type ut on u.user_type_key = ut.user_type_key
inner join t_user_session us
on u.user_key = us.user_key
where u.email = 'tim.super#en.com'
and us.session_id = 'mjsvu6fru3dtfk1bbs59fc8t20'
and us.expired_yn = 'N'
order by 1 desc
Var dump of the result object:
object(mysqli_result)#2 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(3)
["lengths"]=>
NULL
["num_rows"]=>
int(1)
["type"]=>
int(0)
}
I am using similar to the following code to process query/result:
$result = mysqli_query ( $conn, $sql );
if ($result) {
var_dump($result);
if (preg_match('/^[[:space:]]*select/i', $sql) == 1) {
while ($row = mysqli_fetch_assoc ( $result )) {
$return_val[sizeof($return_val)] = $row;
}
if (!clear_results($result)) {
print "error: ".$sql;
}
}
} else {
http_response_code(401);
print $sql . "\n";
print mysqli_error($conn);
die("error");
}
function clear_results($result) {
global $conn;
if ($result) {
if (!mysqli_free_result ( $result )) {
return false;
}
}
while (mysqli_more_results($conn)) {
mysqli_next_result($conn);
mysqli_free_result(mysqli_store_result($conn));
}
return true;
}
I have done a bit off searching around for an answer, but most results are either not clear enough or I find it hard to implement in my current pattern... What I wish to achieve is having a query to select all products from the products table matching a category ID from the category table, But now i wish to also get products that are sub categories of the said parent category. I am using Doctrine 2 with codeigniter and my function so far looks like this
function searchForProducts( $offset, $limit ) {
$search = $this->input->get('search');
$category = (int)$this->input->get('category');
$supplier = (int)$this->input->get('supplier');
for( $i = 0; $i < 2; $i++ ) {
$select = ($i == 0) ? 'count(p)' : 'p';
$qb = $this->em->createQueryBuilder();
$qb ->select($select)
->from(self::ENTITY, 'p');
if( $i != 0) {
$qb ->setFirstResult( (int)$offset )
->setMaxResults( (int)$limit );
}
if( $search ) {
$qb ->where( "p.title LIKE :search" )
->orWhere( "p.sku LIKE :search" )
->setParameter('search', "%$search%");
}
if( $category ) {
$qb ->andWhere( "p.category = ?1" )
->setParameter(1, $category);
}
if( $supplier ) {
$qb ->andWhere( "p.supplier = ?2" )
->setParameter(2, $supplier);
}
if( $i == 0 ) {
$this->totalRows = $qb->getQuery()->getSingleScalarResult();
} else {
return $qb->getQuery()->getResult();
}
}
}
I also don't think it would be practical to get all products then do it from application level as I'm using pagination and products could become quite large.
When you do Product -> Category -> Child Categories -> Product then the resulting Products will not be returned in the same column. Thus Doctrine will hydrate them in the same manor. Which is no good if you want to use pagination on all the products.]
Your best bet is to use a native SQL with result set mapping. Then your query should use a UNION, so that the main Product lines up in the same columns as the child Products
To answer my own question, I decided to take the easy way out, and considering i would only have around 40 categories max, i don't think this should be much of a problem.
In my categories model class i created 2 static methods,
static function getCategoryWithChildren( $id = NULL ) {
$obj = new self;
$parent = $obj->getCategory( $id );
$list = array();
self::iterateCategoriesChildren($parent, $list);
return array_reverse($list);
}
static function iterateCategoriesChildren( $category, &$array ) {
if( $category->hasChildren() ) {
foreach( $category->getChildren() as $child ) {
self::iterateCategoriesChildren($child, $array);
}
}
$array[] = $category;
}
So pretty much this will get the parent and iterate all the children and assign each 1 to the flat array.
Then from my searchProducts method i just added a bit more under the $category check.
if( $category ) {
if( $this->settings->get('product_child_categories') ) {
$categories = Categories_model::getCategoryWithChildren($category);
foreach($categories as $_category) {
$qb ->orWhere( "p.category = " . $_category->getID() );
}
} else {
$qb ->andWhere( "p.category = ?1" )
->setParameter(1, $category);
}
}
May not be best or practical, but it works and does what I need for the time being.