multiple-to-one relationship mysql, submissions
I have the following problem. Basically I have a form with an option to submit up to 3 images. Right now, after each submission it creates 3 records for album table and 3 records for images. I need it to be one record for album and 3 for images, plus to link images to the album. I hope it all makes sense...
Here is my structure.
TABLE `albums` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(50) NOT NULL,
`fullname` varchar(40) NOT NULL,
`email` varchar(100) NOT NULL,
`created_at` datetime NOT NULL,
`theme_id` int(11) NOT NULL,
`description` int(11) NOT NULL,
`vote_cache` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;
TABLE `images` (
`id` int(11) NOT NULL auto_increment,
`album_id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
and my code
function create_album($params)
{
db_connect();
$query = sprintf("INSERT INTO albums set
albums.title = '%s',
albums.email = '%s',
albums.discuss_url = '%s',
albums.theme_id = '%s',
albums.fullname = '%s',
albums.description = '%s',
created_at = NOW()",
mysql_real_escape_string($params['title']),
mysql_real_escape_string($params['email']),
mysql_real_escape_string($params['theme_i开发者_如何学编程d']),
mysql_real_escape_string($params['fullname']),
mysql_real_escape_string($params['description'])
);
$result = mysql_query($query);
if(!$result)
{
return false;
}
$album_id = mysql_insert_id();
return $album_id;
}
if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i]))
{
$warning = 'No file uploaded';
}
elseif is_valid_file_size($_FILES['userfile']['size'][$i])) {
$_POST['album']['theme_id'] = $theme['id'];
create_album($_POST['album']); mysql_query("INSERT INTO images(name) VALUES('$newName')");
copy($_FILES['userfile']['tmp_name'][$i], './photos/'.$original_dir.'/' .$newName.'.jpg');
I must be missing something. Your query to insert images doesn't insert an album id, while that field is mandatory in images
. So that query should fail.
I'm guessing that this is not all of your code and you actually execute a different query to insert the image. If so, that statement probably looks something like this:
$query = "
INSERT INTO images (name, album_id)
VALUES ('albumname', " . create_album($params);
If so, you're creating an album for each image you save. You should save the resulting album id in a variable and use that variable in the three statements that create the image records.
精彩评论