我正在尝试使用 PHP 表单(new.php)来更新 2 个 MySQL 表并从第 3 个表中检索信息。我需要使用 3 个表的原因是可以通过另一种形式(search.php)搜索存储的信息,并且可以轻松编辑信息(edit.php)。
New.php 使用 4 个文本输入字段,目前使用 3 个复选框(尽管一旦我让这 3 个工作正常,这个数字会增加)。复选框充当“标签”,用于描述输入数据库的文章。因此,数据库中的单个条目包含以下信息:
文章标题、文章组织、访问日期、文章 URL 和文章标签(此表还有一id
列。
标题、组织、日期和 url 都存储在一个名为articles
.
标签都存储在一个名为的表中tags
(其中有 85 个)。该表有 2 列:id
和tag_contents
。
第三个表是一个关系表(或者它可能被称为“交集表”?) ,它articles_tags
有 2 列:article_id 和 tag_id。
new.php 当前所做的是将标题、组织、日期和 url 添加到articles
表中,然后mysql_insert_id()
用于获取该条目的 ID。
但是,在那之后,我无法弄清楚我需要用我的复选框做什么。
我有 3 个复选框:
<input type="checkbox" name="articletags[]" value="science" id="articletags_0" />
<input type="checkbox" name="articletags[]" value="geology" id="articletags_1" />
<input type="checkbox" name="articletags[]" value="astronomy" id="articletags_2" />
我需要以某种方式使用这些复选框与文章建立关系。因此,例如,在插入一篇关于岩石的文章后,表单将如下所示:
Article Title: Great new rocks!
Article Organization: US Geology Assoc.
Access Date: 09/20/2012
Article URL: www.rocks.com
Science [X] Geology [X] Astronomy [ ] (note that the X marks a checked checkbox)
而且,数据库表看起来像这样:
(table: articles) id | articletitle | articleorganization | articledate | articleurl
13 | great new rocks! | US geology assoc. | 9/20/2012 | www.rocks.com
(table: tags) id | tag_contents
5 | geology
9 | science
(table: articles_tags) article_id | tag_id
13 | 5
13 | 9
注意tags
table 不会改变,它只存储可用的标签并允许它们被 table 引用articles_tags
。
我无法弄清楚这种情况,我已经研究了一个星期。作为参考,下面添加了 new.php 的代码:
<?php
}
// connect to the database
include('settings.php');
if(count($articletags) > 0)
{
$articletags_string = implode(",", $articletags);
}
// check if the form has been submitted. If it has, start to process the form and save it to the database
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// get form data, making sure it is valid
$articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle']));
$articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization']));
$articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate']));
$articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl']));
// check to make sure both fields are entered
if ($articletitle == '' || $articleorganization == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($articletitle, $articleorganization);
}
else
{
// save the data to the database
mysql_query("INSERT INTO articles SET articletitle='$articletitle',
articleorganization='$articleorganization',
articledate='$articledate',
articleurl='$articleurl' ")
or die(mysql_error());
$article_id = mysql_insert_id();
foreach( $POST_['articletags'] as $newtag )
{
mysql_query('INSERT INTO articles_tags (article_id,tag_id) VALUES ($article_id, $newtag)');
}
// once saved, redirect to success page
header("Location:addsuccess.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','');
}
?>