Exact SQL query returns different data using MySQL Command Line and PHP PDO -


i have query returns last 10 news , last 10 comments each of them database.

sql:

create table news (   news_id int unsigned auto_increment,   subject varchar(128) not null,   article text not null,   type_id tinyint unsigned not null default 1,   news_time timestamp default current_timestamp,   primary key (news_id) );  create table comments (   comment_id int unsigned auto_increment,   message text not null,   news_id int unsigned not null,   msg_time timestamp default current_timestamp,   primary key (comment_id),   constraint fk_comments_news_id foreign key (news_id)     references news (news_id)     on delete cascade );  select news_id, comment_id, rnk (   select     *,     @rnk:=if(@prev_news_id=news_id, @rnk+1, 1) rnk,     @prev_news_id:=news_id   (     select       lastnews.*,       cmts.comment_id,       cmts.message,       cmts.msg_time     (select * news type_id=5 order news_id desc limit 10) lastnews       left outer join comments cmts on cmts.news_id=lastnews.news_id     order cmts.news_id desc, cmts.comment_id desc) t1) t2 rnk <= 10; 

php:

$query = <<<_end select news_id, comment_id, rnk (   select     *,     @rnk:=if(@prev_news_id=news_id, @rnk+1, 1) rnk,     @prev_news_id:=news_id   (     select       lastnews.*,       cmts.comment_id,       cmts.message,       cmts.msg_time     (select * news type_id=5 order news_id desc limit 10) lastnews       left outer join comments cmts on cmts.news_id=lastnews.news_id     order cmts.news_id desc, cmts.comment_id desc) t1) t2 rnk <= 10; _end;  $db = new pdo('mysql:='.db_host.';dbname='.db_name, db_user, db_pass); $dbh = $db->prepare($query); $dbh->execute(); $data = $dbh->fetchall(pdo::fetch_num|pdo::fetch_group); print_r($data); 

the query works in mysql cmd, returns wrong data in php. problem in rnk row. equals 1. why that?

update: restarted mysql command line , broke there. turned on profiling set profiling=1 , works again. more, turning off profiling doesn't negate effect.

it turns out problem user-defined variables initialization. should explicitly avoid undefined behavior. in our case add 1 more join:

from (select * news type_id=5 order news_id desc limit 10) lastnews   left outer join comments cmts on cmts.news_id=lastnews.news_id   inner join (select @rnk:=0,@prev_news_id:=0) t3 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -