开发者

How do I log in and display information from two tables (MySQL)?

I'm new to MySQL and PHP so Im not sure how to approach this problem I'm having.

I have two tables right now.

CREA开发者_运维问答TE TABLE `users` (
  `userid` int(25) NOT NULL AUTO_INCREMENT,
  `username` varchar(65) NOT NULL DEFAULT '',
  `password` varchar(32) NOT NULL DEFAULT '',
  `emailaddress` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

and

CREATE TABLE `images` (
  `userid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `image` blob,
  PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

so what I want to do is when a user signs in I want to be able to display an image that the user uploaded.

do I have to do something to the tables to make theme reference from each other?

help please!


Do you want just?...

select image from images 
left join users on users.userid=images.userid 
where username='whateverusername';


in the second table , the attribute userid should be a foreign key (i'd rather use Innodb to make sure that there is a foreign key constraint but it's up to u to use innodb or not)

so your table should look like this

CREATE TABLE images (
userid int(10) unsigned NOT NULL,
name varchar(50) DEFAULT NULL,
image blob,
foreign key userid references users(userid) on delete cascade
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

once you do that, the table images will be linked to the table users which means that no record will be added to the table images unless the user id is already in the table users

if you wanna grab all the informations about that users including the image , you can perform a join between the two tables.

example with php

$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
     die('Could not connect: ' . mysql_error());
}
$user_id = 1;
$results = array(); 
> $results =mysql_query("select t1.userid,t1.username,t2.name,t2.image   from users as t1  left join images as t2 on t1.userid=t2.userid  where userid = $user_id",$con);

UPDATE: make sure that the type of userid in both tables match

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜