How to write mysql OR query using codeigniter - php

I have product table with product name and foreign key column named as subcategory I want to get product based on subcategory id and product name using or condition in codeigniter query method I wrote query for that but it is retrieving two record but i need only one record
for example we have table:
productid product subcategory
1 A 1
2 A 3
3 B 3
$var="some value from form(1 or 3)";
case 1: if product='A' and subcategory($var)=1 or subcategory ($var)=3 then it should get record with productid=1
case2 :if product='A' and subcategory($var)=2 or subcategory ($var)=3 then it should get record for productid=2 because we are using or condition it should check 1 or 3
the query which I have used it is retrieving two records but I need only one record if subcategory =1 or 3
Query:
$this->db->where('product', 'A');
$where = '(subcategory="1" or subcategory = "3")';
$this->db->where($where);
$this->db->get('product');
$query = $gsm_pricing = $query->row();

This query solved my issue
$this->db->query(select * from product where product='A'
and subcategory='1'
union all
select * from product where product='A' and subcategory='3'
and not exists(select 1 from product where subcategory='1' and prodduct='A'));

Try using " group by productid " in your Query

Related

model relation with and without foreign key

please ignore syntax errors
im working on a system with these tables
products : id , title
1 p1
custom_field : id , title
10 color
11 something all products have
custom_field_attach : custom_field_id , product_id
10 1
11 0
i want to get product custom fields
i can have this relation in Product model
function CustomFields(){
return $this->belongsToMany(CustomField::class , 'custom_field_attach');
}
and have this query
$product = Product::with('CustomFields')->get();
but the thing is some custom_fields are for all the products so in the custom_field_attach table
product_id is 0for those custom_fields
sine my relation is using product_id as foreign key i wont get those rows with product_id = 0 in the result
basically i want
custom_field_attach where product_id = product.id OR product_id = 0
to make thisng simpler i can have this relation in Product model
function CustomFieldAttach(){
return $this->hasMany(CustomFieldAttach::class);
}
no i want something like
$product = Product::with(['CustomFieldAttach' => function($CustomFieldAttach){
// where forieng key works product_id=product.id orWhere product_id =0
}])->get();
i know i can do this with query builder but i want to use relation if possible
please note someone else has written this code and im just adding some features to the system ... changing the db structure is not an option

How can i use sql count in these multiple tables?

I am still a php/mysql newbie and I am working on mysql table relationship concept and i am having an issue with using mysql count in multiple table. Here is my db structure.
**product table**
id product_name product_img groupeid
1 Sneaker Mark sneaker_adi.png 1
2 bag Eric bageric.png 2
3 Sneaker Etoi sneakeretoi.jpg 1
**groupe table**
group_id group_name
1 men
2 women
**category table**
catid catname
1 sneaker-shoes
2 bag-woman
**productcategory table**
prod_id cat_ID
1 1
2 2
3 1
What i want to do is to determine the number of sneaker-shoes using mysql.
We can see that the number of sneaker-shoes in the db is 2.
But how can i use **count()** in these multiple tables.
I tried like this;
$sql = "SELECT COUNT(*) product.id,product_name,catname FROM product INNER JOIN productcategory ON product.id = prod_id INNER JOIN category ON catid = cat_ID WHERE catname='sneaker-shoes'";
i got error like:
Fatal error: Call to a member function execute() on a non-object in C:\wamp\www\kbashopping\Homme\index.php on line 32
Hope i exposed the issue clearly, any help and assistance will be appreciate
Thanks
If you are looking only for the count, mention only the count phrase in the Select clause.
Change :
SELECT COUNT(*) product.id,product_name,catname FROM
to :
SELECT COUNT(product.id) FROM
SELECT count (pc.cat_ID) FROM productcategory pc inner join category c on c.catid = pc.cat_ID where c.catname = 'sneaker shoes';
This will build a temporary table in mysql that joins category and product category but only including results where the catname is sneaker shoes. Then it selects a column to run the count operation on, and returns the result of count.

mysql 2 tables updation/deletion based on condition

Hello friends I have 2 Mysql tables with 1:N relationship between category and category_Dates
Category:
ID Category Frequency
1 Cat A Half-yearly
2 Cat B Quarterly
category_Dates:
ID CatID Date
1 1 01-Jan-15
2 1 01-Jul-15
3 2 01-Jan-15
4 2 01-Apr-15
5 2 01-Jul-15
6 2 01-Oct-15
based on the category frequency I am entering number of records automatically in category_date. Eg
When category frequency = quarterly, I am entering 4 records in category_date with ID of that category. And dates will be entered later.
I am little confused if in case on wants to edit the frequency from halfyearly to yearly. How to change number of records. Please help with your valuable suggestions. I am using laravel 4 framework with mysql
best way would be with 3rd table joining Dates and Categories. See little carefully ,you can see its actually Many to Many relationship (N to N) as 1 category can have multiple dates. and one date may be part of multiple categories, like say 01-Jan-15 is part of Category 1 and 2 as well.
So use
category table
id Category Frequency
1 Cat A Half-yearly
2 Cat B Quarterly
date table
id Date
1 01-Jan-15
2 01-Apr-15
3 01-Jul-15
4 01-Oct-15
categories_dates table
ID CatID Date_id
1 1 1
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4
If you change the frequency in Category table, retrieve the update category_id,
delete all from category_dates where CatId=category_id then insert the new entries in category_Dates.
Hope this help.
I assume your models are Category and CategoryDates.
let's update category id 1 from Half-yearlyto to Quarterly
$query = Category::find(1);
$query -> Frequency = 'Quarterly';
$query -> save();
return $query -> id;
in the CategoryDates model you would delete the catID = 1 and insert new data
$catID = 1;
$query = CategoryModel::where('CatId',$catId) -> delete();
$data = ['CatId' => $catID,'date' => 01-Jan-15, ....];
CategoryModel::create($data);
of course assuming that you would return the newly updated category id to your controller and call a funtionn to do the update in your CategoryModel.
Hope this help.

Only get one occurance of a table row in mysql php based on id

I have a table that looks like this
id | itemID | catID | Title
----------------------------------------------------------------------------
0 3 4 Hello
1 3 6 Hello
2 4 4 Yo
3 4 8 Yo
4 5 2 Hi
5 1 3 What
I want to do a MySQL PHP Select that only gets one occurrence of the itemID. As you can see they are the same item, just in different categories.
This is what I tried
SELECT * FROM Table GROUP BY itemID
That didn't seem to work, it still just shows duplicates.
Is this what you are looking for? http://www.sqlfiddle.com/#!2/5ba87/1
select itemID, Title from test group by itemID;
As far as MySQL is concerned, the data is all unique, since you want all of the columns. You have to be more specific.
Do you just want the itemID (or other column)? Then say so:
select [column] from Table GROUP BY itemID
Do you want the last entry of a particular item ID? Then say that:
select * from Table where itemID = 1 ORDER BY id DESC
Or the first one?
select * from Table where itemID = 1 ORDER BY id
If none of these are what you want, then you probably need to restructure your tables. It looks like you want different categories for your items. If so, then you'll want to split them out into a new join table, because you have a many-to-many relationship between Items and Categories. I recommend reading up on database normalization, so you're not duplicating data (such as you are with the titles).
If you want everything for the distinct itemIDs, you could certainly take a long route by doing one selection of all of the distinct itemIDs, then doing a series of selections based on the first query's results.
select distinct(`itemID`) from Table
Then in your PHP code, do something like this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$itemID = $row['itemID'];
$sql2 ="SELECT * FROM Table WHERE 1 and `itemID`=\"$itemID\" limit 1";
$result2 = #mysql_query($sql2, $connection);
while ($row2 = mysql_fetch_array($result2))
{
$id = $row2['id'];
$itemID = $row2['itemID'];
$catID = $row2['catID'];
$Title = $row2['Title'];
}
}

how to get value from mysql table ordered by another table?

i have some reference to record for a given article. a reference might be of type an article, book, thesis etc..
each might have different attributes, e.g.
//article_refs table
ID Article_ID Article_Title Author_Name ...
1 1 title1 author1
2 1 title2 author2
//thesis_refs table
ID Article_ID Thesis_Title Thesis_Publisher ...
1 1 thesis1 publisher1
2 1 thesis2 publisher2
//ref_types table
ID Article_ID ReferenceType
1 1 book
2 1 article
3 1 article
4 1 book
when i insert into one of the tables, i first into ref_type table with its type (book, article). then insert whichever table it belongs. (e.g. if it is an article, insert into article table)..
now, i have to be able list references in order.
$sql=mysql_query("SELECT * FROM ref_types
WHERE $article_ID=Article_ID ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$counter=1;
if($row[2]=="thesis"){
$sqlthesis=mysql_query("SELECT * FROM thesis_refs
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
while($thesis_row = mysql_fetch_array($sqlthesis)){
echo "record $counter: ";
echo $row[2];
echo ", ";
echo $thesis_row[2];
echo "<BR>";
$counter++
}
}elseif.....
this way it lists all thesis records then lists article table etc..
record 1: book1
record 2: book2
record 3: article1
record 4: article2
i know it is simply because of while loop, but how to get this (same order with ref_types table..)??
record 1: book1
record 2: article1
record 3: article2
record 4: book2
any help is appreciated.
thanks in advance..
In addition to having ReferenceType column in ref_types table, you also need a Reference_ID column that refers to the actual ID in the corresponding table as a foreign key.
//ref_types table
ID Article_ID ReferenceType Reference_ID
1 1 book 1
2 1 article 1
3 1 article 2
4 1 book 2
Then, you can avoid a WHILE loop and let MySQL do the work for you with JOINs:
SELECT CONCAT('record ', rt.ID, ': ',
COALESCE(ar.Article_Title, tr.Thesis_Title, br.Book_Title))
FROM ref_types rt
LEFT JOIN article_refs ar
ON rt.ReferenceType = 'article' AND ar.ID = rt.Reference_ID
LEFT JOIN book_refs br
ON rt.ReferenceType = 'book' AND br.ID = rt.Reference_ID
LEFT JOIN thesis_refs tr
ON rt.ReferenceType = 'thesis' AND tr.ID = rt.Reference_ID
Yields the result:
record 1: book1
record 2: article1
record 3: article2
record 4: book2
Instead of printing the data right away, store it in an array based of the ref_thesis id. e.g
$data = array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE $article_ID=Article_ID ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$counter=1;
if($row[2]=="thesis"){
$sqlthesis=mysql_query("SELECT * FROM ref_thesis
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
while($thesis_row = mysql_fetch_array($sqlthesis)){
$data[ $row['id'] ] = $row;
}
}elseif.....
that way the rows in the $data array will be in the order based on the id in the ref_thesis table.
That said, I think you should go back and think about the db schema you have. You should be able to get what you want with a few simple JOIN statements in a single query, rather than querying the db inside a while loop

Categories