Convert a $_GET value in PDO - sql

I wrote a basic function to join 3 tables regarding a similar id.
{
$id = $_GET["id"];
$product_edit_query = $this->DB->query('
SELECT * FROM products
LEFT JOIN products_ingredients
ON products_ingredients.product_id = products.product_id
LEFT JOIN products_languages
ON products_languages.product_id = products.product_id
WHERE products.product_id = 73
');
$product_edit = $product_edit_query->fetch();
$this->smarty->assign('product_edit', $product_edit);
}
In the last line I have of my request, i have WHERE products.product_id = 73. 73 is hardcoded, and should be the value of $_GET["id"], but all I tried didn't work to convert it in PDO, any help ?

Solution given by a friend:
{
$stmt = $this->DB->prepare('
SELECT * FROM products
LEFT JOIN products_ingredients
ON products_ingredients.product_id = products.product_id
LEFT JOIN products_languages
ON products_languages.product_id = products.product_id
WHERE products.product_id = :id
');
$stmt->execute([':id' => $_GET["id"]]);
$get_product_base = $stmt->fetch();
$this->smarty->assign('get_product_base', $get_product_base);
}

Related

How to do a SQL JOIN where multiple joined rows need to contain things

When someone on my site search for an image that has multiple tags I need to query and find all images that have the searched tags, but can't seem to figure out this query.
I have an Images table.
The Images table has a relation to Posts_Images.
Posts_Images would have a relation to Posts table.
Posts has a relation to Posts_Tags table.
Posts_Tags table will have the relations to Tags table.
The query I have so far:
SELECT "images".* FROM "images"
INNER JOIN "posts_images" ON posts_images.image_id = images.id
INNER JOIN "posts" ON posts.id = posts_images.post_id AND posts.state IS NULL
INNER JOIN "posts_tags" ON posts_tags.post_id = posts.id
INNER JOIN "tags" ON posts_tags.tag_id = tags.id
WHERE (("images"."order"=0) AND ("images"."has_processed"=TRUE)) AND (LOWER(tags.tag)='comic') AND ("tags"."tag" ILIKE '%Fallout%') ORDER BY "date_uploaded" DESC LIMIT 30
It gets no results, it is checking if the tags equals both values, but I want to see if any of the tags that were joined have all the values I need.
The desired result would be any Post that has a tag matching Comic and ILIKE '%Fallout%'
You seem to want something like this:
SELECT i.*
FROM images JOIN
posts_images pi
ON pi.image_id = i.id JOIN
posts p
ON p.id = pi.post_id AND p.state IS NULL JOIN
posts_tags pt
ON pt.post_id = p.id JOIN
tags t
ON pt.tag_id = t.id
WHERE i."order" = 0 AND
i.has_processed AND
(LOWER(t.tag) = 'comic') OR
(t.tag ILIKE '%Fallout%')
GROUP BY i.id
HAVING COUNT(DISTINCT tag) >= 2
ORDER BY date_uploaded DESC
LIMIT 30;
The logic is in the HAVING clause. I'm not 100% sure that this is exactly what you want for multiple matches.
In addition to gordon-linoff’s response - query can be described using ActiveQuery:
Images::find()
->alias('i')
->joinWith([
'postsImages pi',
'postsImages.posts p',
'postsImages.posts.tags t'
])
->where([
'p.state' => null,
'i.order' => 0,
'i.has_processed' => true,
])
->andWhere(
'or'
'LOWER(t.tag) = "comic"',
['like', 't.tag', 'Fallout']
])
->groupBy('id')
->having('COUNT(DISTINCT tag) >= 2')
->orderBy('date_uploaded DESC')
->limit(30)
->all()
$images = Images::find()
->innerJoin('posts_images', 'posts_images.image_id = images.id')
->innerJoin('posts', 'posts.id = posts_images.post_id AND posts.state IS NULL')
->where(['images.order' => 0, 'images.has_processed' => true]);
if (!is_null($query)) {
$tags = explode(',', $query);
$images = $images
->innerJoin('posts_tags', 'posts_tags.post_id = posts.id')
->innerJoin('tags', 'posts_tags.tag_id = tags.id');
$tagsQuery = ['OR'];
foreach ($tags as $tag) {
$tag = trim(htmlentities($tag));
if (strtolower($tag) == 'comic') {
$tagsQuery[] = ['tags.tag' => $tag];
} else {
$tagsQuery[] = [
'ILIKE',
'tags.tag', $tag
];
}
}
if (!empty($tagsQuery)) {
$images = $images->andWhere($tagsQuery)
->having('COUNT(DISTINCT tags.tag) >= ' . sizeof($tags));
}
}
$images = $images
->groupBy('images.id')
->orderBy(['date_uploaded' => SORT_DESC])
->offset($offset)
->limit($count);
return $images->all();

Codeigniter: from sql to activerecord, what is the wrong?

I want to try change my sql code to active record, here is the original code and active record try. And the error message. Please tell me where is my wrong? Thanks.
SELECT `emlakilan`.`id`, `emlakdurum`.`durum`,`emlaktip`.`tip`,`semtler`.`semt`,`emlakilan`.`fiyat`,`emlakilan`.`tarih`,`resim`.`r1` FROM ucburcak.`emlakilan`
INNER JOIN `semtler` ON `emlakilan`.`semtId` = `semtler`.`semtid`
INNER JOIN `emlaktip` ON `emlakilan`.`emlakTipId` = `emlaktip`.`id`
INNER JOIN `emlakdurum` ON `emlakilan`.`emlakDurumId` =`emlakdurum`.`id`
LEFT JOIN `resim` ON `emlakilan`.`resimId` = `resim`.`id`
WHERE `emlakdurumId`=3 ORDER BY `emlakilan`.`id` DESC LIMIT 4;
//and here active record function
public function kucuk_ilan($durum ='3') // $durum:1=>tümü 2=>kiralık 3=>satılık 4=>takas
{
$query = $this->db->select('emlakilan.id, emlakdurum.durum, emlaktip.tip, semtler.semt, emlakilan.fiyat, emlakilan.tarih, resim.r1')
->from('emlakilan')
->join('semtler','emlakilan.semtId' === 'semtler.semtid','inner')
->join('emlaktip','emlakilan.emlakTipId'==='emlaktip.id','inner')
->join('emlakdurum','emlakilan.emlakDurumId'==='emlakdurum.id','inner')
->join('resim','emlakilan.resimId'==='resim.id','left')
->where('emlakdurumId'===$durum)
->order_by('emlakilan.id','desc')
->limit(4);
$query = $this->db->get('emlakilan');
return $query->result_array();
}
And, error message:
Error Number: 1066
Not unique table/alias: 'emlakilan'
SELECT emlakilan.id, emlakdurum.durum, emlaktip.tip, semtler.semt, emlakilan.fiyat, emlakilan.tarih, resim.r1 FROM (emlakilan, emlakilan) INNER JOIN semtler ON INNER JOIN emlaktip ON INNER JOIN emlakdurum ON LEFT JOIN resim ON WHERE 0 IS NULL ORDER BY emlakilan.id desc LIMIT 4
Filename: C:\Program Files\EasyPHP-12.1\www\3burcak\system\database\DB_driver.php
Line Number: 330
Thanks for help.
So 1. remove the 'from' line
2. the joins where wrong
try this:
public function kucuk_ilan($durum ='3') // $durum:1=>tümü 2=>kiralık 3=>satılık 4=>takas
{
$query = $this->db->select('emlakilan.id, emlakdurum.durum, emlaktip.tip, semtler.semt, emlakilan.fiyat, emlakilan.tarih, resim.r1')
->from('emlakilan')
->join('semtler','emlakilan.semtId = semtler.semtid','inner')
->join('emlaktip','emlakilan.emlakTipId = emlaktip.id','inner')
->join('emlakdurum','emlakilan.emlakDurumId = emlakdurum.id','inner')
->join('resim','emlakilan.resimId = resim.id','left')
->where('emlakdurumId', $durum)
->order_by('emlakilan.id','desc')
->limit(4);
$query = $this->db->get('emlakilan');
return $query->result_array();
}

Complex SQL to LINQ conversion with subquery

I am trying to convert this expression into LINQ from SQL, but a bit too difficult for me, maybe you can help me with this!
SELECT TOP (2) RecipeID, UserID, Name, Servings, PreparationTime, TotalTime, DifficultyLevelID, CuisineID, DishID, MainIngredientID, PriceLevelID, FlavourID, Instructions,
Notes, Thumbnail, VideoLink
FROM dbo.Recipes
WHERE (RecipeID NOT IN
(SELECT DISTINCT Recipes_1.RecipeID
FROM dbo.Allergies INNER JOIN
dbo.UsersAllergies ON dbo.Allergies.AllergyID = dbo.UsersAllergies.AllergyID INNER JOIN
dbo.IngredientsAllergies ON dbo.Allergies.AllergyID = dbo.IngredientsAllergies.AllergyID INNER JOIN
dbo.Ingredients ON dbo.IngredientsAllergies.IngredientID = dbo.Ingredients.IngredientID INNER JOIN
dbo.RecipesIngredients ON dbo.Ingredients.IngredientID = dbo.RecipesIngredients.IngredientID INNER JOIN
dbo.Recipes AS Recipes_1 ON dbo.RecipesIngredients.RecipeID = Recipes_1.RecipeID INNER JOIN
dbo.Users ON dbo.UsersAllergies.UserID = dbo.Users.UserID INNER JOIN
dbo.AllergyFactors ON dbo.IngredientsAllergies.AllergyFactorID = dbo.AllergyFactors.AllergyFactorID
WHERE (dbo.Users.UserID = 3) AND (dbo.AllergyFactors.AllergyFactorID < 3)))
It would be easier to help you if you showed us what you have already tried, but a Linq expression like this should give you the same result set
var query = (from rec in context.Recipes
where !(from al in context.Allergies
from ua in context.UsersAllergies.Where(x => al.AllergyID == x.AllergyID)
from ia in context.IngredientsAllergies.Where(x => al.AllergyID == x.AllergyID)
from in in context.Ingredients.Where(x => ia.IngredientID == x.IngredientID)
from ri in context.RecipesIngredients.Where(x => in.IngredientID == x.IngredientID)
from re in context.Recipes.Where(x => ri.RecipeID == x.RecipeID)
from us in context.Users.Where(x => ua.UserID == x.UserID)
from af in context.AllergyFactors.Where(x => ia.AllergyFactorID == x.AllergyFactorID)
where us.UserID == 3 && af.AllergyFactorID < 3
select re.RecipeID)
.Distinct()
.Contains(rec.RecipeID)
select new
{
rec.RecipeID,
rec.UserID,
rec.Name,
rec.Servings,
rec.PreparationTime,
rec.TotalTime,
rec.DifficultyLevelID,
rec.CuisineID,
rec.DishID,
rec.MainIngredientID,
rec.PriceLevelID,
rec.FlavourID,
rec.Instructions,
rec.Notes,
rec.Thumbnail,
rec.VideoLink
}).Take(2);

Zend how do I create a left join

How do I turn this left join query:
select advertisercontest.*, advertiseraccount.advertiserid, advertiseraccount.companyname
from advertisercontest
left join advertiseraccount on advertiseraccount.loginid = advertisercontest.loginid
where advertisercontest.golive is not NULL;
into a left join in Zend?
You could do as follows:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('advertisercontest', '*')
->joinLeft(
'advertiseraccount',
'advertiseraccount.loginid = advertisercontest.loginid',
array('advertiseraccount.advertiserid', 'advertiseraccount.companyname')
)
->where('advertisercontest.golive is not NULL');;
$result = $db->fetchAll($select);
var_dump($result);
Here is the Zend_Db_Select documentation.

Querying Wordpress thumbnails

I am trying to get the thumbnail meta data for the posts in my wordpress blog together with their category and some other data.
The thumbnail data is serialized and I will unserialize it later.
Here is the query I have:
SELECT wpostmeta.meta_value AS url,
wposts.post_content, wposts.post_title, wposts.post_status, wposts.post_name,
cat_terms.name AS category_name, cat_terms.term_id AS category_id,
ttable.meta_value AS thumb_data
FROM `wp_postmeta` AS wpostmeta,
`wp_posts` AS wposts
INNER JOIN wp_term_relationships AS cat_term_relationships ON (wposts.ID = cat_term_relationships.object_id)
INNER JOIN wp_term_taxonomy AS cat_term_taxonomy ON (cat_term_relationships.term_taxonomy_id = cat_term_taxonomy.term_taxonomy_id AND cat_term_taxonomy.taxonomy = 'category')
INNER JOIN wp_terms AS cat_terms ON (cat_term_taxonomy.term_id = cat_terms.term_id)
LEFT JOIN `wp_postmeta` AS ttable ON (wposts.ID = ttable.post_id AND ttable.meta_key = '_wp_attachment_metadata')
WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = 'url'
AND wposts.post_type = 'post'
Everything works except for the attachment part. 'thumb_data' is NULL.
Could you please help me fix this?
This query solved my problem:
$sql = "SELECT wposts.ID AS ID, thumbposts.ID AS thumbposts_ID,
postmeta.meta_value AS url,
wposts.post_content, wposts.post_title, wposts.post_status, wposts.post_name,
cat_terms.name AS category_name, cat_terms.term_id AS category_id,
thumb.meta_value AS thumb_data
FROM `wp_postmeta` AS postmeta,
`wp_posts` AS thumbposts,
`wp_postmeta` AS thumb,
`wp_posts` AS wposts
INNER JOIN wp_term_relationships AS cat_term_relationships ON (wposts.ID = cat_term_relationships.object_id)
INNER JOIN wp_term_taxonomy AS cat_term_taxonomy ON (cat_term_relationships.term_taxonomy_id = cat_term_taxonomy.term_taxonomy_id AND cat_term_taxonomy.taxonomy = 'category')
INNER JOIN wp_terms AS cat_terms ON (cat_term_taxonomy.term_id = cat_terms.term_id)
WHERE wposts.ID = postmeta.post_id
AND postmeta.meta_key = 'url'
AND thumbposts.post_parent = wposts.ID
AND thumbposts.post_type = 'attachment'
AND thumb.post_id = thumbposts.ID
AND thumb.meta_key = '_wp_attachment_metadata'
AND wposts.post_type = 'post'";
if($filter == 1){
$sql .= " AND cat_terms.term_id = '1'";
}
if($filter == 2){
$sql .= " AND cat_terms.term_id = '3'";
}
$sql .= " GROUP BY wposts.ID
ORDER BY wposts.post_date ASC";
Can you explain exactly what you are trying to achieve - there is no real need to go direct to the database in the vast number of situations.
For example you can use get_posts with 'post_type'=>'attachment' and 'post_mime_type'=>'image' to get image attachments and then output the metadata, and there are many functions inbuilt to deal with resizing, displaying and cropping the thumbnails, such as get_post_thumbnail() etc.