将处理 PHP 表单复选框发布到 MySQL 表中 [英] Issue processing PHP form checkboxes into MySQL table

查看:49
本文介绍了将处理 PHP 表单复选框发布到 MySQL 表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用复选框的 PHP 表单.我还有一个包含 3 个表的 MySQL 数据库.

其中一个表名为 TAGS,其列是 ID 和 ARTICLE_CONTENTS.

数据库中的另一个表称为 ARTICLES,其列是 ID、ARTICLETITLE、ARTICLEORGANIZATION、ARTICLEDATE 和 ARTICLEURL.

第三个表称为ARTICLES_TAGS,它的列是ARTICLE_ID和TAG_ID

TAGS 表有 87 个类似于以下内容的条目:

1 |地质学2 |天文学3 |化学

数据库的目的是在标签和文章之间建立关系.为此,PHP 表单使用用户在向数据库添加新条目时可以检查的复选框.这些复选框代表 TAGS 表中的标签.因此,例如,TAGS 表中的每个条目都有一个复选框:[ ]geology [ ]astronomy [ ]chemistry ...等...

我想要做的是使用文本框(文章标题、文章组织、文章日期和文章网址)插入信息,并使用 mysql_insert_id() 获取该插入的 ID 并将该 ID 与与选中的复选框关联的标记的 ID.

因此,例如,如果要选中地质复选框,并且如果在 TAGS 表中地质条目是:

02 |地质学

而且,如果插入的文章的 ID 恰好是 142

然后

一个新条目将被插入到 ARTICLES_TAGS 中:

Article_ID |TAG_ID142 |02

然而,每当我执行我的表单时,虽然信息正确插入到了 ARTICLES 表中,但我在 ARTICLES_TAGS 表中没有任何条目.我不知道我哪里出错了.

几天来我一直在研究这个问题的措辞,我认为现在已经很清楚了.如果需要澄清,请告诉我.

代码是:

<!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"><头>...<身体><div class="容器"><div class="header">...

<div class="sidebar1">...

<div class="内容"><div id="风格化" class="myform"><form id="form" name="form" action="" method="post"><h1>在数据库中创建一个新条目</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">文章标题:</span></td><td width="80%" align="left"><span class="field"><input name="articletitle" type="text" value="<?php echo $articletitle; ?>"大小=50"/></span></td></tr><tr><td align="right"><span class="field">文章作者:</span></td><td align="left"><span class="field"><input name="articleorganization" type="text" value="<?php echo $articleorganization; ?>"大小=50"/></span></td></tr><tr><td align="right"><span class="field">访问日期:</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">文章网址:</span></td><td align="left"><span class="field"><input name="articleurl" type="text" value="<?php echo $articleurl; ?>"大小=50"/></span></td></tr><tr><td align="right"><span class="field">文章标签:</span></td><td align="left"><span class="field"><input type="checkbox" name="articletags[]" value="1" id="articletags_0"/>科学<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="添加这篇文章"/></td></tr></表单>

<div class="footer">...

</html><?php}包括('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 = '错误:请填写所有必填字段!';renderForm($articletitle, $articleorganization);}别的{mysql_query("插入文章SET articletitle='$articletitle',文章组织='$文章组织',文章日期='$文章日期',articleurl='$articleurl'");$article_id = mysql_insert_id();foreach ($_POST['articletags'] 作为 $newtag){mysql_query(" INSERT INTO article_tags article_id='$article_id',tag_id='$newtag'");}header("位置:addsuccess.php");}}别的{renderForm('','','','','');}?>

解决方案

开始工作...

首先,您需要修复一个解析错误.

第 93 行:

mysql_query("插入文章SET articletitle='$articletitle',文章组织='$文章组织',文章日期='$文章日期',articleurl='$articleurl'")$article_id = mysql_insert_id();或死(mysql_error());header("位置:addsuccess.php");

注意$article_id = mysql_insert_id() 赋值之后的or die().这是无效的语法.

mysql_query("插入文章SET articletitle='$articletitle',文章组织='$文章组织',文章日期='$文章日期',articleurl='$articleurl'")或死(mysql_error());$article_id = mysql_insert_id();header("位置:addsuccess.php");

第 84 - 85 行:

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

这个块是问题所在:你有一个什么都不做的循环.但是,您已经准备好插入语句.因此,让我们将此循环与第 101 行(在 101 的位置)合并以进行有效插入.

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

您的结果应如下所示:

<!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"><头>...<身体><div class="容器"><div class="header">...

<div class="sidebar1">...

<div class="内容"><div id="风格化" class="myform"><form id="form" name="form" action="" method="post"><h1>在数据库中创建一个新条目</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">文章标题:</span></td><td width="80%" align="left"><span class="field"><input name="articletitle" type="text" value="<?php echo $articletitle; ?>"大小=50"/></span></td></tr><tr><td align="right"><span class="field">文章作者:</span></td><td align="left"><span class="field"><input name="articleorganization" type="text" value="<?php echo $articleorganization; ?>"大小=50"/></span></td></tr><tr><td align="right"><span class="field">访问日期:</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">文章网址:</span></td><td align="left"><span class="field"><input name="articleurl" type="text" value="<?php echo $articleurl; ?>"大小=50"/></span></td></tr><tr><td align="right"><span class="field">文章标签:</span></td><td align="left"><span class="field"><input type="checkbox" name="articletags[]" value="1" id="articletags_0"/>科学<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="添加这篇文章"/></td></tr></表单>

<div class="footer">...

</html><?php}包括('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 = '错误:请填写所有必填字段!';renderForm($articletitle, $articleorganization);}别的{mysql_query("插入文章SET articletitle='$articletitle',文章组织='$文章组织',文章日期='$文章日期',articleurl='$articleurl'")或死(mysql_error());$article_id = mysql_insert_id();header("位置:addsuccess.php");}foreach( $_POST['articletags'] 作为 $newtag ){mysql_query('INSERT INTO article_tags (article_id,tag_id) VALUES ($article_id, $newtag)');}}别的{renderForm('','','','','');}?>

现在它可以工作了...

我们必须先讨论一下安全问题.到目前为止,对于初学者来说,您已经做得很好,但是您错过了转义一个被插入(逐字!)到查询中的变量:tag_id.你忘了单引号不插入值.

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

真的应该(主要是为了安全):

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

一点点优化

当您插入大量标签时,此脚本会创建多个查询.所以我想我会向您展示如何清理它以一次插入多个标签.

if(isset($POST_['articletags']) && count($POST_['articletags'])) {$query = '插入文章标签(文章ID,标签ID)值';$tags = array();foreach( $POST_['articletags'] 作为 $newtag ){$tags[] = sprintf('(%d, %d)', $article_id);}mysql_query($query .implode(', ', $tags));}

此代码生成与之前相同的查询,但它会构建一组列表以一次插入多个条目.最重要的是,它还将两个值都过滤为整数.

代码格式

我不得不重新格式化一下才能理解你的代码.这部分是您的问题的原因.如果没有适当的缩进,您可能很容易错过这样的错误并且永远不会知道.您可能想阅读编程风格.

I have a PHP form that uses checkboxes. I also have a MySQL database with 3 tables.

One of the tables is named TAGS and its columns are ID and ARTICLE_CONTENTS.

Another table in the database is called ARTICLES and its columns are ID, ARTICLETITLE, ARTICLEORGANIZATION, ARTICLEDATE, and ARTICLEURL.

The third table is called ARTICLES_TAGS and its columns are ARTICLE_ID and TAG_ID

The TAGS table has 87 entries that are similar to:

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. These checkboxes represent the tags in the TAGS table. So, for example, there would be a checkbox for each entry in the TAGS table: [ ]geology [ ]astronomy [ ]chemistry ...etc...

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.

So, for instance, if the geology checkbox were to be checked and if, in the TAGS table the entry for geology were to be:

02  |  geology

And, if the ID for the article being inserted happened to be 142

Then

a new entry would be inserted into 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. 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:

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(). 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:

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.

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. 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.

这篇关于将处理 PHP 表单复选框发布到 MySQL 表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆