简体   繁体   English

将处理PHP表单复选框发布到MySQL表中

[英]Issue processing PHP form checkboxes into MySQL table

I have a PHP form that uses checkboxes. 我有一个使用复选框的PHP表单。 I also have a MySQL database with 3 tables. 我也有一个带有3个表的MySQL数据库。

One of the tables is named TAGS and its columns are ID and ARTICLE_CONTENTS. 其中一张表名为TAGS,其列为ID和ARTICLE_CONTENTS。

Another table in the database is called ARTICLES and its columns are ID, ARTICLETITLE, ARTICLEORGANIZATION, ARTICLEDATE, and ARTICLEURL. 数据库中的另一个表称为ARTICLES,其列为ID,ARTICLETITLE,ARTICLEORGANIZATION,ARTICLEDATE和ARTICLEURL。

The third table is called ARTICLES_TAGS and its columns are ARTICLE_ID and TAG_ID 第三个表称为ARTICLES_TAGS,其列为ARTICLE_ID和TAG_ID

The TAGS table has 87 entries that are similar to: TAGS表具有87个条目,它们类似于:

1    |    geology
2    |    astronomy
3    |    chemistry

The purpose of the database is to create relationships between the TAGS and the ARTICLES. 数据库的目的是在标签和文章之间建立关系。 To do this, the PHP form uses checkboxes that the user can check when adding a new entry to the database. 为此,PHP表单使用复选框,用户可以在向数据库添加新条目时选中该复选框。 These checkboxes represent the tags in the TAGS table. 这些复选框代表TAGS表中的标签。 So, for example, there would be a checkbox for each entry in the TAGS table: [ ]geology [ ]astronomy [ ]chemistry ...etc... 因此,例如,TAGS表中的每个条目都会有一个复选框:[]地质[]天文学[]化学...等...

What I'm trying to do is to insert information using text boxes (article title, article organization, article date, and article url) and to use mysql_insert_id() to get the ID of that insertion and to pair that ID with the ID of the tag associated with the checkboxes that are checked. 我想做的是使用文本框(文章标题,文章组织,文章日期和文章url)插入信息,并使用mysql_insert_id()获取该插入的ID并将该ID与ID配对与选中的复选框关联的标签。

So, for instance, if the geology checkbox were to be checked and if, in the TAGS table the entry for geology were to be: 因此,例如,如果要选中“地质”复选框,并且在“ TAGS”表中是否要输入“地质”:

02  |  geology

And, if the ID for the article being inserted happened to be 142 并且,如果插入的文章的ID恰好是142

Then 然后

a new entry would be inserted into ARTICLES_TAGS: 新条目将插入ARTICLES_TAGS:

Article_ID    |    TAG_ID
   142        |      02

However, whenever I execute my form I get no entries in the ARTICLES_TAGS table though the information INSERTs into the ARTICLES table properly. 但是,每当我执行表单时,尽管信息已正确插入ARTICLES表,但ARTICLES_TAGS表中没有任何条目。 I can not figure out where I've gone wrong. 我无法弄清楚哪里出了问题。

I've been working on the wording of this question for a few days and I think it's clear now. 我一直在研究这个问题的措辞几天,我认为现在很清楚。 Please let me know if there needs to be any clarification. 请让我知道是否需要任何澄清。

The code is: 代码是:

<?php
    function renderForm($articletitle, $articleorganization, $articledate, $articleurl, $articletags )
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    . . .
</head>
    <body>
        <div class="container">
        <div class="header">
            . . .
        </div>
        <div class="sidebar1">
            . . .
        </div>
        <div class="content">
            <div id="stylized" class="myform">
                <form id="form" name="form" action="" method="post">
                    <h1>Create a new entry in the database</h1>
                        <table width="76%" border="0" cellpadding="6">
                            <tr>
                                <td colspan="2"><legend></legend></td>
                            </tr>
                            <tr>
                                <td width="20%" align="right"><span class="field">Article Title:</span></td>
                                <td width="80%" align="left"><span class="field">
                                    <input name="articletitle" type="text" value="<?php echo $articletitle; ?>" size="50"/>
                                </span></td>
                            </tr>
                            <tr>
                                <td align="right"><span class="field">Article Author:</span></td>
                                <td align="left"><span class="field">
                                    <input name="articleorganization" type="text" value="<?php echo $articleorganization; ?>" size="50"/>
                                </span></td>
                             </tr>
                             <tr>
                                 <td align="right"><span class="field">Access Date:</span></td>
                                 <td align="left"><span class="field">
                                     <input name="articledate" type="text" value="MM/DD/YYYY" size="50"/>
                                 </span></td>
                             </tr>
                             <tr>
                                 <td align="right"><span class="field">Article URL:</span></td>
                                 <td align="left"><span class="field">
                                     <input name="articleurl" type="text" value="<?php echo $articleurl; ?>" size="50"/>
                                 </span></td>
                             </tr>
                             <tr>
                                 <td align="right"><span class="field">Article Tags:</span></td>
                                 <td align="left"><span class="field">
                                     <input type="checkbox" name="articletags[]" value="1" id="articletags_0" />Science
                                     <input type="checkbox" name="articletags[]" value="2" id="articletags_1" />Geology

                                 </span></td>
                             </tr>
                             <tr>
                                 <td colspan="2" align="center" valign="middle"><input type="submit" name="submit" value="Add this Article" /></td>
                             </tr>
                        </table>
                </form>
        </div>
       <div class="footer">
           . . .
       </div>
    </body>
</html>
<?php 
}
    include('settings.php');

    if(count($articletags) > 0)
{
    $articletags_string = implode(",", $articletags);
}
    if($_SERVER['REQUEST_METHOD'] == 'POST')
{ 
    $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']));
{
}
    if ($articletitle == '' || $articleorganization == '')
{
    $error = 'ERROR: Please fill in all required fields!';
    renderForm($articletitle, $articleorganization);
}
    else
{
    mysql_query("INSERT INTO articles SET articletitle='$articletitle',
        articleorganization='$articleorganization',
        articledate='$articledate',
        articleurl='$articleurl' ");
    $article_id = mysql_insert_id();       

    foreach ($_POST['articletags'] as $newtag)
{
    mysql_query(" INSERT INTO articles_tags article_id='$article_id',
               tag_id='$newtag' ");
}
    header("Location:addsuccess.php");  
}
}
    else
{
    renderForm('','','','','');
}
?>

Getting it working... 开始运作...

Firstly, you've a parse error to fix. 首先,您要解决一个解析错误。

Line 93: 第93行:

mysql_query("INSERT INTO articles SET articletitle='$articletitle',
    articleorganization='$articleorganization',
    articledate='$articledate',
    articleurl='$articleurl' ")
    $article_id = mysql_insert_id();       
or die(mysql_error()); 
header("Location:addsuccess.php"); 

Note the or die() after the assignment of $article_id = mysql_insert_id() . 注意分配$article_id = mysql_insert_id()之后的or die() $article_id = mysql_insert_id() This is invalid syntax. 这是无效的语法。

mysql_query("INSERT INTO articles SET articletitle='$articletitle',
    articleorganization='$articleorganization',
    articledate='$articledate',
    articleurl='$articleurl' ")
    or die(mysql_error()); 
$article_id = mysql_insert_id();       
header("Location:addsuccess.php"); 

Line 84 - 85: 84-85行:

foreach( $POST_['articletags'] as $newtag )
{
}

This block is the problem: you have a loop doing nothing. 这个问题是问题:您有一个循环什么也不做。 However, you do have the insert statement ready to go. 但是,您确实已准备好插入语句。 So let's merge this loop with line 101 (at 101's position) to make a working insertion. 因此,让我们将此循环与第101行(位于101的位置)合并以进行有效插入。

foreach( $_POST['articletags'] as $newtag )
{
  mysql_query('INSERT INTO articles_tags (article_id,tag_id) VALUES ($article_id, $newtag)');
}

Your result should look like this: 您的结果应如下所示:

<?php
    function renderForm($articletitle, $articleorganization, $articledate, $articleurl, $articletags )
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    . . .
</head>
    <body>
        <div class="container">
        <div class="header">
            . . .
        </div>
        <div class="sidebar1">
            . . .
        </div>
        <div class="content">
            <div id="stylized" class="myform">
                <form id="form" name="form" action="" method="post">
                    <h1>Create a new entry in the database</h1>
                        <table width="76%" border="0" cellpadding="6">
                            <tr>
                                <td colspan="2"><legend></legend></td>
                            </tr>
                            <tr>
                                <td width="20%" align="right"><span class="field">Article Title:</span></td>
                                <td width="80%" align="left"><span class="field">
                                    <input name="articletitle" type="text" value="<?php echo $articletitle; ?>" size="50"/>
                                </span></td>
                            </tr>
                            <tr>
                                <td align="right"><span class="field">Article Author:</span></td>
                                <td align="left"><span class="field">
                                    <input name="articleorganization" type="text" value="<?php echo $articleorganization; ?>" size="50"/>
                                </span></td>
                             </tr>
                             <tr>
                                 <td align="right"><span class="field">Access Date:</span></td>
                                 <td align="left"><span class="field">
                                     <input name="articledate" type="text" value="MM/DD/YYYY" size="50"/>
                                 </span></td>
                             </tr>
                             <tr>
                                 <td align="right"><span class="field">Article URL:</span></td>
                                 <td align="left"><span class="field">
                                     <input name="articleurl" type="text" value="<?php echo $articleurl; ?>" size="50"/>
                                 </span></td>
                             </tr>
                             <tr>
                                 <td align="right"><span class="field">Article Tags:</span></td>
                                 <td align="left"><span class="field">
                                     <input type="checkbox" name="articletags[]" value="1" id="articletags_0" />Science
                                     <input type="checkbox" name="articletags[]" value="2" id="articletags_1" />Geology
                                 </span></td>
                             </tr>
                             <tr>
                                 <td colspan="2" align="center" valign="middle"><input type="submit" name="submit" value="Add this Article" /></td>
                             </tr>
                        </table>
                </form>
        </div>
       <div class="footer">
           . . .
       </div>
    </body>
</html>
<?php 
}
    include('settings.php');

    if(count($articletags) > 0)
    {
        $articletags_string = implode(",", $articletags);
    }

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    { 
        $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']));
        if ($articletitle == '' || $articleorganization == '')
        {
            $error = 'ERROR: Please fill in all required fields!';
            renderForm($articletitle, $articleorganization);
        }
        else
        {
            mysql_query("INSERT INTO articles SET articletitle='$articletitle',
                articleorganization='$articleorganization',
                articledate='$articledate',
                articleurl='$articleurl' ")
                or die(mysql_error()); 
            $article_id = mysql_insert_id();       
            header("Location:addsuccess.php");  
        }
        foreach( $_POST['articletags'] as $newtag )
        {
          mysql_query('INSERT INTO articles_tags (article_id,tag_id) VALUES ($article_id, $newtag)');
        }
    }
    else
    {
    renderForm('','','','','');
    }
?>

Now that it works... 现在可以了...

We've got to discuss security for just a second. 我们只需要讨论安全性一秒钟。 You've done well so far for a beginner, but you've missed escaping one variable that gets inserted (verbatim!) into the queries: the tag_id. 到目前为止,对于初学者来说,您做得很好,但是您错过了转义插入查询的一个变量(tag!id):tag_id。 And you forgot that single-quotes do not insert values. 而且您忘记了单引号不会插入值。

mysql_query('INSERT INTO articles_tags (article_id,tag_id) VALUES ($article_id, $newtag)');

Should really be (primarily for security): 确实应该(主要是出于安全性):

mysql_query(sprintf('INSERT INTO articles_tags (article_id,tag_id) VALUES (%d, %d)', $article_id, $newtag));

A little optimization 一点优化

When you're inserting a lot of tags this script creates multiple queries. 当您插入大量标签时,此脚本会创建多个查询。 So I figured that I'd show you how to clean it up to insert multiple tags at once. 因此,我想到了向您展示如何清除它以一次插入多个标签。

if(isset($POST_['articletags']) && count($POST_['articletags'])) {
  $query = 'INSERT INTO articles_tags (article_id,tag_id) VALUES ';
  $tags = array();
  foreach( $POST_['articletags'] as $newtag )
  {
    $tags[] = sprintf('(%d, %d)', $article_id);
  }
  mysql_query($query . implode(', ', $tags));
}

This code generates the same query as before, but it will build a set of lists to insert multiple entries at once. 该代码生成与以前相同的查询,但是它将构建一组列表以一次插入多个条目。 On top of that, it also filters both values into integers. 最重要的是,它还将两个值都过滤为整数。

Code formatting 代码格式化

I had to do a little reformatting to understand your code. 我必须重新格式化才能理解您的代码。 This is partly the cause of your problem. 这部分是造成您问题的原因。 Without proper indentation you might miss errors like this easily and never know. 没有适当的缩进,您可能会轻易错过此类错误,并且永远不会知道。 You might want to read up on programming style . 您可能需要阅读编程风格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM