doujiao1948 2013-12-18 21:10
浏览 81
已采纳

PHP表单成功发布到MySQL数据库,但添加空白行

I have searched, incessantly, for a fix to the problem of a PHP form causing blank rows in a MySQL database (of which my search query was, "form submitting blank rows to mysql database" here on SO). I find that I'm having the problem REGARDLESS of the fact that I constructed a suitable "post/redirect/get" pattern;

PHP Form Page (input.php) ---> 
PHP Form Processing Page (backend.php) ---> 
Database Entry Results Display page (thanks.php - return link to index.php set also)

The problem of the blank row submission escapes me as I've attempted to add validation to the form so that there are no empty submissions, whether the page was reloaded (via back button or otherwise) and do the standard isset() checks.

PHP Form (input.php)

    <form name="input" action="backend.php" method="post">
    <font color="#0000CC" face="arial black">Article/News Title:</font><br>
    <input type="text" name="Title" size="35" />
    <br><br>
    <font color="#0000CC" face="arial black">Article/News URL:</font><br>
    <input type="text" name="Link" value="http://" size="40" />
    <br><br>
    <font color="#0000CC" face="arial black">Article/News description</font> <font size="4" color="#0000CC">(300 Characters Max)</font><br>
    <TABLE style="BORDER-RIGHT: #000000 1px ; BORDER-TOP: #000000 1px ; BORDER-LEFT: #000000 1px ; WIDTH: 100px; BORDER-BOTTOM: #000000 1px ; BORDER-COLLAPSE: separate; BACKGROUND-COLOR: #ffffff" cellSpacing=0 cellPadding=0 border=0 alignment="">
   <TBODY>
   <TR>
   <TD style="BORDER-RIGHT: #000000 1px solid; PADDING-RIGHT: 3px; BORDER-TOP: #000000 1px solid; PADDING-LEFT: 3px; PADDING-BOTTOM: 3px; BORDER-LEFT: #000000 1px solid; PADDING-TOP: 3px; BORDER-BOTTOM: #000000 1px solid">
    <textarea id="bob" rows="8" name="Body" cols="60"></textarea>
    <script language="JavaScript">
    generate_wysiwyg("bob");
    </script>
    </TD></TR></TBODY></TABLE>
    <br>
    <font color="#0000CC" face="arial black">Article/News Category?</font><br>
    <SELECT name="category">
    <OPTION>games
    <OPTION>hardware
    <OPTION>humor
    <OPTION>movies
    <OPTION>music
    <OPTION>online
    <OPTION>politics
    <OPTION>programming
    <OPTION>radio
    <OPTION>science
    <OPTION>social
    <OPTION>software
    <OPTION>sports
    <OPTION>technology
    <OPTION>television
    </SELECT>
    <br><br>
    <input type="submit" name="submit" value="Input"></form>

PHP Form Processing (backend.php)

    // Connect to database
   $con=mysql_connect("localhost","db_user","pwd") or die(mysql_error("Cannot Connect To Database"));
   mysql_select_db('db_name', $con) or die(mysql_error("Cannot Select Database"));
   if (isset($_POST['submit'])) {

   // Define query variables
   $ArticleTitle = mysql_real_escape_string(strip_tags($_POST['Title']));
   $ArticleBody = mysql_real_escape_string(stripslashes($_POST['Body']));
   $ArticleLink = mysql_real_escape_string(strip_tags($_POST['Link'],'<a>'));
   $ArticleCategory = mysql_real_escape_string($_POST['category']);

   // Sets the timestamp format
   $Datum = date('D - M. j - g:ia');
   }

    //CHECK FOR EMPTY FIELDS 
    if (empty($_POST["Title"]) or empty($_POST["Body"]) or empty($_POST["Links"]) or empty($_POST["category"])) {

    $error =''; 
    if (trim($_POST['Title'])==''){ 
     $error .= "<li>Please enter a title</li>"; 

    } elseif (trim($_POST['Body'])==''){ 
      $error .= "<li>Please enter some content</li>"; 

    } elseif (trim($_POST['Link'])==''){ 
      $error .= "<li>Please enter a URL</li>"; 

    } elseif (trim($_POST['category'])==''){ 
      $error .= "<li>Please enter a category</li>"; 

    } else {

    //IF NO ERRORS DO SQL QUERY
    $query1=sprintf("INSERT INTO articles (title, link, body, date, category) VALUES ('%s', '%s', '%s', '%s', '%s')", $ArticleTitle, $ArticleLink, $ArticleBody, $Datum, $ArticleCategory);

    // Execute the query or die and echo an error message
    mysql_query($query1) or die("Unable to execute query:" . mysql_error());

    if ($query1) {
    include("thanks.php");
    }
    else {
    header('Location: input.php');
        }
      }
    }
    mysql_close($con);

Entry Result Display Page (thanks.php)

    echo "Your Article/News URL Has Been Posted - Thank You!";
    echo "<br /><br /><b>";
    echo $_POST['Title'];
    echo "</b><br /><br /><b>";
    echo $_POST['Body'];
    echo "</b><br /><br /><b>";
    echo $_POST['Link'];
    echo "</b><br /><br /></b>";
    echo $_POST['Date'];
    echo "</b><br /><br /><b>";
    echo $_POST['category'];
    echo "</b><br /><br />";
    echo "<a href='index.php'><font face='arial black' size='2' color='#0000CD'><u>Return To Articles</u></font></a>";

I have no problem with the end display, and this PRG pattern works insanely well except for the blank row additions which manifest several minutes to hours later. When debugging, I would let 24 hrs go by sometimes, and all was good. But the blank row would multiply (all with stated NULL values when I accessed PHPMyAdmin). I'm convinced that the logic in backend.php is skewed in some weird fashion. I have rewritten that page at least twenty times (four different versions of the page gave me my desired db output). There has got to be something that I'm missing, but after nearly thirty days of straight "search-and-code", I haven't been able to suss it out.

Yes, I know I'm working with deprecation, but I can't begin a complete PDO rewrite on my app until I can get this last issue sorted, and (believe me), it's BEGGING for it (lol!). I think it's relevant to mention also that input.php is protected by a PDO login script preventing random site visitors from posting willy-nilly. The only two problems that I can think that I'm having is that;

1) The visitation of input.php while in a non-logged state is tripping the form submission process (or some searchbot traffic, for that matter),

or

2) Correct coding/wrong placement

All I need is a pointer to how I could solve this. I appreciate any and every reply. Thanks.

EDIT

OK, you know what, I've noticed that the other ancillary pages carrying information to the categories and their sub-headings (i.e - category:Programming / Sub-Headings: new/old/most/least - the php pages under the particular category topic - each one having its' own folder to keep those four pages grouped together), NEVER EVER have displayed the problem that the index.php has just errored out on so I may just have to change how the data comes out of the database by trashing the idea of trying to display the code on the front page. That would actually give me lattitude to do something uber-cool and include in some insanely small app that I've battle-tested and KNOW that works in the trenches, since, even as propellor-headed and code-tweakled I am, I'm still trying to upgrade my ability to make myself a living and actually continue to eat off this enterprise we call "Web Development" (lol!)

  • 写回答

2条回答 默认 最新

  • douji1999 2014-01-06 07:04
    关注

    Two things helped me in the process of finding my answer;

    A) The conversion of my PHP processing page to PDO;

        <?php
        if (isset($_POST['submit'])) {
        $ArticleTitle = $ArticleLink = $ArticleBody = $ArticleCategory = $Datum = '';
    
        // Define a boolean and set to true before validating
        $formValid = true;
    
        // Data pulled from input form
        $ArticleTitle = $_POST['title'];
        $ArticleLink = $_POST['link'];
        $ArticleBody = $_POST['body'];
        $ArticleCategory = $_POST['category'];
    
        //Set date parameters
        $Datum = date('D - M. j - g:ia');
    
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
        if ($_POST['title'] == null OR trim($_POST['title']) ==''|| $_POST['link'] == null OR trim($_POST['link']) =='' || $_POST['body'] == null OR trim($_POST['body']) =='' || $_POST['category'] == null OR trim($_POST['category']) =='') {
            echo '<br><br><div align="center"><a href="input.php"><font color="#0000CC" face="arial black">Please return to form and supply required data!</font></a><br><img src="http://www.promodrone.com/images/myimage.gif"></div>';
            $formValid = false; // Invalid input - set the flag to false
            exit;
            } else {
    
            if ($formValid){
    
            //PDO connection string details
            try {
            $dsn = 'mysql:host=localhost;dbname=dbname';
            $username ='user_name';
            $password ='pwd';
            $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE =>PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES, false); 
            $dbh = new PDO($dsn, $username, $password, $options);
            } catch (Exception $e) {
            echo "WTF?!" . $e->getMessage('Cannot connect: ' . mysql_error());
            }
             //Insert data into db
                try {
                $sth = $dbh->prepare('INSERT INTO articles(title, link, body, category, date) VALUES (?, ?, ?, ?, ?)');
                $sth->execute(array($ArticleTitle, $ArticleLink, $ArticleBody, $ArticleCategory, $Datum));
    
                //If successful redirect to display database insertion details
                if($sth){
                exit(include('thanks.php'));
                }                 
                else{
                echo '<a href="input.php"><font color="#0000CC" face="arial black">No record added. Return to form, please!</font></a>';
                }
                } catch (Exception $e) {
                echo "Glugh?!" . $e->getMessage('Cannot continue:  <a href="input.php"><font color="#0000CC" face="arial black" size="3">Return to form, please!</font></a>' . mysql_error());
                }
                }
                }
                }
                } 
                $dbh = NULL;
                ?>
    

    and, B) that you have to check SUPER-THOROUGHLY so you don't commit errors caused by overlooking.

    On my index.php page, I didn't close a table correctly and, somehow, that kept helping to insert an extra (empty) row in the database. I was only led there this afternoon, after I took a spin at another coding website I have an account with. For some reason, I was compelled to look at the HTML table structure. My forehead is STILL sore from the nuclear facepalm after my realization;

                 echo "<p style='font-size:95%'><b>Category -</b><b>";
                 echo "</b></p></table></center><br>";
    

    NOT

                 echo "<p style='font-size:95%'><b>Category -</b><b>";
                 echo "</p></b></font></table></center><br>";
    

    The only thing that I'm NOT happy about is I had to destroy my nice little "P/R/G" pattern, since I couldn't (no matter what I tried), get the vars from the processing page (backend.php) to be echoed from the thanks.php page. The reason for this is that when a user finishes entering the details of their article/news URL, the thanks php is supposed to present them with their input;

                 $ArticleTitle    (Article/News title)
                 $ArticleLink     (Article/News link)
                 $ArticleBody     (Article/News content/image body)
                 $ArticleCategory (Article/News category)
    

    stacked exactly in the above fashion. Since earlier this afternoon, I've played the complete paranoiac (lol), because I jumped the gun and celebrated too early the night before. My solution has held for me since this afternoon, and the same error described above in the HTML table had been replicated to all the other category index pages. After changing them all in one fell swoop via my IDE, I tested rigorously by adding ten more entries back to back (about three hours ago), and I haven't even seen the problem pop-up again. :deep sigh: (lol!). Hope this helps someone. I don't know if this is even SLIGHTLY off-topic (and I'm sure that someone will let me know), but the time of MySQL is FINISHED. I understand why many people aren't gung-ho on PHP Data Objects, but after a period of seven days straight on it, it began to "talk" to me. I'M - NEVER - GOING - BACK.....now, to rewrite the rest of the application (lol!).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题