我正在用MySQL练习PHP,我正在创建一个网页,列出查询表中的所有详细信息——这部分非常有效。然后,我希望用户能够单击表中的链接,这将引导用户指向该特定表条目的CRUD页面。
我所拥有的代码与我的原始页面结合起来很好,但是,由于我试图将其中的3个表连接在一起,这会使我的事情变得复杂。我现在拥有的工作代码只适用于一个表。我正在努力想出一些想法,关于如何更改我的代码,以便它能方便我使用联接的三个表。
以下是我的表格:
演出场地sname sname snam(这些不包含相同的值。)id(2)id id(1)第(2)幕场馆(1)
现在是代码分解。
这是允许我更新表中的条目的代码(尽管我希望它更新3而不是1)
if (!count($errors)) {
// Data is valid and can be committed to database
if ('Update' == $_REQUEST['action']) {
$show = 'table';
// Data for gig can be safely updated
$sql = 'UPDATE gig SET sname=:sname, start=:start
WHERE id=:id';
$res = $db->prepare($sql);
if (!$res->execute(array(':sname' => $details['sname'],
':id' => $details['id'],
':start' => $details['start'],
))) {
$errors['sql'] = sprintf("%s (id %s) could not be updated",htmlentities($_POST['sname']),$_POST['id']);
$show = 'form';
} else {
$status = sprintf("%s updated",htmlentities($details['sname']));
}
现在是从网页创建新条目的代码。同样,这段代码只插入一个表的数据,而不是我想要的3。但我们会在底部找到答案。
} else { // Create action
// Data for gig can be safely created
$sql = 'INSERT INTO gig (id,sname,start)
VALUES (:id,:sname,:start)';
$res = $db->prepare($sql);
if (!$res->execute(array(':sname' => $details['sname'],
':id' => $details['id'],
':start' => $details['start'],
))) {
$errors['sql'] = sprintf("%s (id %s) could not be created (Has the id already been used?)",htmlentities($_POST['country']),$_POST['id']);
$show = 'new';
} else {
$status = sprintf("%s created",htmlentities($details['sname']));
}
}
}
因此,我正试图实现,在我的代码中实现的三个列(sname),我知道它们都有冲突,但当我设法打印出3条评论中的所有细节时,我绕过了这一点。
这就是密码。
SELECT g.id AS gig_id, g.sname AS gig_name, v.sname AS venue_name, a.sname AS act_name FROM gig AS g, venue AS v, act AS a WHERE g.venue=v.id AND g.act=a.id
基本上,我想问的是,我该如何调整上述语句以符合我的CRUD语句,我希望我已经解决了问题部分,我只需要朝着正确的方向前进?
提前感谢您的帮助。
您可以使用类似以下的查询来实现这一点:
/* insert */
insert into venue values ();
set @gig_venue := LAST_INSERT_ID();
insert into act values ();
set @gig_act := LAST_INSERT_ID();
insert into gig values(@gig_venue, @gig_act /*, etc */);
/* update */
select venue, act from gig where id = @gig_id into @venue, @act;
update venue set foo=1 where id = @venue;
update act set bar=1 where id = @act;
update gig set baz=1 where id = @gig_id;
/* update in a single statement (no way to do with insert though)*/
update gig
join venue on venue.id = gig.venue
join act on act.id = gig.act
set foo=1,
bar=2;
但是,您要么需要将它们放在事务中,要么非常小心地在失败时实现手动回滚。