duanmibei1929 2012-06-20 16:16
浏览 55
已采纳

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

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('','','','','');
}
?>
  • 写回答

1条回答 默认 最新

  • dqst96444 2012-06-20 16:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器