Doctrine Why this query return 0 rows? - php

I have the following DQL query:
$q = Doctrine_Query::create()
->select('id')
->from('Comment')
->where("active='?' AND object_id='?' AND group_name = '?'"
, array(1, 1, 'unit'));
Which produce the sql:
SELECT c.id AS c__id, c.group_name AS c__group_name, c.name AS c__name,
c.email AS c__email
FROM comment c
WHERE (c.active = '?' AND c.object_id = '?' AND c.group_name = '?')
bindings: 1, 1, unit
In database table:
id user_id object_id group_name name active
1 0 1 unit test 1
When I execute de query it returns 0 rows. Why?
If I go in phpmyadmin and I run
SELECT * FROM comment WHERE active=1 AND object_id=1 AND group_name='unit'
the result contains the record I look for.
In phpmyadmin the query generated by Doctrine identify the table name as 'c'. This is very strange, since I used in my application other DQL querys like this one and works.
Thanks.

Remove quotes around parameter placeholders:
where("active=? AND object_id=? AND group_name = ?"
or use named parameters:
where("active= :ative AND object_id= :object_id AND group_name = :group_name"
, array(':ative'=>1, ':objet_id'=>1, 'group_name'=>'unit')"

Related

PHP/SQL: How to concatenate/combine columns value into one row

I have this php script called title, where it is supposed to list movie details of those movies with the title matching the inputed substring. The expected output is supposed to be like in the link/picture below. I have trouble with concatenating the genres of each movies since one movie can have many genres. I have tried using the concat(), array_to_string() but still fails.
mkSQL() constructs "safe" SQL query strings by taking a query template
string and filling in printf-like slots in the template with values
supplied in subsequent arguments. The function takes a variable number
of arguments; the first is always a query template string, with the
following arguments corresponding exactly to the slots in the
template. E.g.
$id = 3012345;
$q1 = mkSQL("select * from R where id = %d",$id);
would create the query strings:
$q1: "select * from R where id = 12345"
Below are the codes, any helps and tips will be greatly appreciated, thanks!
This is the Genre Table Schema
CREATE TABLE Genre (
movie_id integer REFERENCES Movie(id),
genre GenreType,
primary key (movie_id,genre));
#!/usr/bin/php
<?php
// include the common PHP code file
require("a2.php");
$db = pg_connect("dbname=mydb");
// Check arguments
if (count($argv) < 2) exit("$usage\n");
// Get the return results
$val = $argv[1];
$q = "select m.title, m.year, m.content_rating, r.imdb_score, array_to_string(array(select g.genre FROM Genre g where g.movie_id = m.id),',')
-- concat(select g.genre FROM Genre g where g.movie_id = m.id
from Movie m JOIN Rating r ON r.movie_id = m.id
where m.title ilike %p
order by m.year, r.imdb_score desc, m.title asc";
$r = pg_query($db, mkSQL($q, $val));
// Iterate through the results and print
$i = 1;
while ($t = pg_fetch_array($r)) {
echo "$i. $t[0] ($t[1], $t[2], $t[3]) [$t[4]]\n";
$i++;
}
?>
The expected output is supposed to be in this format
Change your query like,
SELECT CONCAT(m.title, ' (', m.year, ', ', m.content_rating, ',', r.imdb_score, ') [', (SELECT array_to_string(array_agg(g.genre), ',') FROM Genre g WHERE g.movie_id = m.id), ']') movie_title
FROM Movie m JOIN Rating r ON r.movie_id = m.id
WHERE m.title ilike %p
ORDER BY m.year, r.imdb_score desc, m.title ASC
Here, I have concat all columns into one and given it an alias movie_title. You will get the movie name as per your specified format.
For achieving this, you can use the group_concat function in your mysql script.
This will concatenate your respective column via comma(,).

Mysql query IN clause return results

Good Day! All Fridays,
I have some problem in my sql query. I'm using IN class with subquery like this
SELECT
cm.category_id,
cd.name
FROM
category_master cm,
category_detail cd,
brand_to_categories b2c
WHERE
cm.category_id = b2c.category_id
AND
cd.category_id = cm.category_id
AND
cd.language_id = 1
AND
cm.status <> 2
AND
cm.category_id IN (SELECT DISTINCT sub_dd.categories FROM distribution_master bdm, distribution_detail bdd, subscription_category_to_brand_user sub_dd WHERE bdd.distribution_id = bdm.distribution_id AND bdm.distributor_id = 35 AND bdd.brand_id = 7191 AND sub_dd.sub_d_id = bdd.id)
AND
b2c.brand_id = 7191;
The following is the sub-query which is creating problem for me.
cm.category_id IN (
SELECT DISTINCT
sub_dd.categories
FROM
distribution_master bdm,
distribution_detail bdd,
subscription_category_to_brand_user sub_dd
WHERE
bdd.distribution_id = bdm.distribution_id
AND
bdm.distributor_id = 35
AND
bdd.brand_id = 7191
AND
sub_dd.sub_d_id = bdd.id)
the result of the sub-query is like this.
3913,4517,6059,7137,7138,7139,7140,7141,7144
this result is coming from only single row in the target table because I stored these ids as string in the filed.
Now the problem is this, I can not get results of the all categories. Main query final result only return one category information which category_id is 3913. But if I run this query manually with sub-query values instead of the sub-query then it returns all the categories results.
Manual query with sub-query values is like this
SELECT
cm.category_id,
cd.name
FROM
category_master cm,
category_detail cd,
brand_to_categories b2c
WHERE
cm.category_id = b2c.category_id
AND
cd.category_id = cm.category_id
AND
cd.language_id = 1
AND
cm.status <> 2
AND
cm.category_id IN (3913,4517,6059,7137,7138,7139,7140,7141,7144)
AND
b2c.brand_id = 7191;
Please help me regarding this problem.
Sorry I forget, I'm using Mysql
Assuming you are using MySQL, use FIND_IN_SET:
WHERE
...
FIND_IN_SET(cm.category_id,
(SELECT DISTINCT sub_dd.categories
FROM distribution_master bdm,
distribution_detail bdd,
subscription_category_to_brand_user sub_dd
WHERE bdd.distribution_id = bdm.distribution_id AND
bdm.distributor_id = 35 AND
bdd.brand_id = 7191 AND
sub_dd.sub_d_id = bdd.id)) > 0
If you are using SQL Server, then we have to do a bit more work:
WHERE ',' + (SELECT DISTINCT ...) + ',' LIKE '%,' + cm.category_id + ',%'
General comment: Avoid storing CSV data in your SQL tables. MySQL almost made the problem worse by offering FIND_IN_SET and making it easier to skirt good table design.

How can I order the results of an SQL query by the count of another table based on a shard ID?

I have an SQL query that fetches posts from a database. Everything works fine, but now I need to order the results by the number of comments each post has. The comments are on a separate table and they have a post_id column that links it to the post. I need to order the posts by the count of the comments table based on a shard ID? I have tried everything but every time I try to add something to my query it stops running completely and leaves my page blank. I need help to know where to put the other JOIN statement. This is my query:
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) ";
The comments table is called wallcomments and it has a column called post_id. I know I need to use JOIN and COUNT but I don't know where to put it within my current code.
Try this query, I didn't run but i updated it.
SELECT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) " AND wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id.";
A more readable query might look like this...
At least then we'd have a chance.
SELECT DISTINCT p.p_id
, p.is_profile_notes
, p.times_viewed
, p.columnTimesShared
, p.marked
, p.secure_id
, p.media...
FROM wallposts p...

Eloquent multiple select in the same query

Doing my firsts steps in eloquent, I'm trying to achieve a query that retrieve some data and count some conditions at the same time.
This raw SQL sentence works as expected
SELECT *
FROM photos,
(SELECT COUNT(*) FROM photos where type = 1 and published =1 group by type) as qA,
(SELECT COUNT(*) FROM photos where type = 2 and published =1 group by type) as qP
where product_id = 7
and published = 1
But using Photo model I can't get the same results
Photo::select(*,
Photo::raw('count(*) where type = 1 and published =1 group by type as qA),
Photo::raw('count(*) where type = 2 and published =1 group by type as qP))
->where ('product_id',7)
->where('published', 1)
->get()
Stripping out "raw" sentences, this query works, but I need to count those "type" ocurrences.
Thanks in advance for any guide over it.
Do you really need to get all in one query? Does it make sense for your application? I mean, I guess those types count are not really information about the record(s?) you are fetching (product_id = 7), rather they are general information about the state of the table as a whole.
If this makes sense, you could try
$photo = Photo::where ('product_id',7)
->where('published', 1)
->get();
$types_count = Photo::where('published', 1)
->selectRaw('type, COUNT(*) AS count')
->groupBy('type')
->get()
->keyBy('type');
$qA = $types_count[1]->count;
$qP = $types_count[2]->count;

Laravel 4 union generate wrong SQL

Here is the code:
$f = DB::table("topics")
->join("recommends", "topics.id", "=", "recommends.courseid")
->where("recommends.re_type", "=", $re_type)
->where("recommends.re_location", "=", $re_location)
->orderBy("recommends.weigh", "desc");
$s = DB::table("topics")
->orderBy("topics.create_time", "desc");
$f->union($s)->get();
I got a wrong SQL around key word union:
select * from `topics` inner join `recommends`
on `topics`.`id` = `recommends`.`courseid`
where `recommends`.`re_type` = ?
and `recommends`.`re_location` = ?
order by `recommends`.`weigh` desc
union //here!!!!!
select * from `topics` order by `topics`.`create_time` desc
The error info:
SQLSTATE[HY000]: General error: 1221
Incorrect usage of UNION and ORDER BY (SQL: ...)
(Bindings: array ( 0 => 3, 1 => 7, ))
What is the problem?
MySQL UNIONs expect the same columns in all statements. Because you're joining another table in $f, the columns between the two statements don't match.
See MySql SELECT union for different columns?
In this case, it might be less of a headache to use the PDO object directly.
$pdo = DB::connection()->getPdo();
Found another problem with your query. You should relocate your first order by clause:
->orderBy("recommends.weigh", "desc");
It is producing the order by you before union and MySQL will not accept that.

Categories