php - Correct mysql query to query one table and have that provide information for another table query -
i have 2 separate tables, both of need query simultaneously correct information display. tables members , posts. through html form, user enters criteria members table, , need use primary index of specific members find posts submitted members , sort on posts table results. results mixture of rows 2 tables. both tables have primary index of name 'id'. far i've come is:
$sql_get_posts = mysqli_query($link, "(select id, username members active='y' , gender='m' , city='yuma' , state='arizona') union (select * posts member_id='id' , active='y' order list_weight desc)") or die(mysqli_error($link)); the error i'm getting "the used select statements have different number of columns".
i need cycle through returned results both tables populate content seen user:
<?php while ($row = mysqli_fetch_array($sql_get_posts)) { $post_id = $row['id']; //this should post primary index named 'id', not member primary index name 'id' $member_id = $row['member_id']; //this member_id row in post table referencing particular member wrote post $member_username = $row['username']; //this row stored in member table $title = $row['title']; //this row stored in post table ******//and on , on getting rows post table } edit sql tables:
create table if not exists `members` ( `id` int(11) not null auto_increment, `username` varchar(20) not null, `age` varchar(3) not null, `gender` varchar(1) not null, `city` varchar(20) not null, `state` varchar(50) not null, `active` enum('y','n') not null default 'y', `created_date` timestamp not null default current_timestamp on update current_timestamp, primary key (`id`) ) engine=myisam default charset=latin1 auto_increment=3 ; create table if not exists `posts` ( `id` int(11) not null auto_increment, `member_id` int(11) not null, `title` text not null, `comments` enum('y','n') not null default 'y', `post_date` timestamp not null default current_timestamp on update current_timestamp, `list_weight` double not null, `active` enum('y','n') not null default 'y', primary key (`id`) ) engine=myisam default charset=latin1 auto_increment=47 ;
use join instead of union, union assumes tables you're combining similar, whereas join merges columns of 2 tables.
something like:
select members.id, members.username, posts.* members inner join posts on members.id = posts.member_id members.active='y' , members.gender='m' , members.city='yuma' , members.state='arizona' order posts.list_weight desc
Comments
Post a Comment