表单提交后对数组的行和列验证

时间:2012-11-20 22:46:30

标签: php for-loop

我有两个PHP文件:

1)simplearraypost.php(包含表格)
  2)echoarraypost.php(表格的验证)

表单有3列,

1)行号
2)项目编号
3)描述

现在,如果发布了,则需要对每个行的单元格进行验证。列!

两者的代码分别粘贴在这里。

simplearraypost.php

<html>
<body>
  <form name="insertitem" method="post" action="echoarraypost.php">
  <table border="1">
    <thead>
      <tr>
        <th>Row No.</th>
        <th>Item</th>
        <th>Description</th>
      </tr>
    </thead>
<?php
  // Number of rows
  $number = 10;

  // Create rows
  for ($i = 1; $i <= $number; $i++) {
    echo '      <tr>' . "\n";
    echo '        <td align="right">' . $i . '</td>' . "\n";
    echo '        <td><input type="text" name="itemno[]" size="5"></td>' . "\n";
    echo '        <td><input type="text" name="description[]" size="50"></td>' . "\n";
    echo '      </tr>' . "\n";
  }
?>
    <tr>
      <td colspan="4" align="right"><input type="submit" name="submit" value="Submit" /></td>
    </tr>
  </table>
  </form>
</body>
</html>

echoarraypost.php

<?php
  // store all posted item numbers and descriptions in local arrays
  $itemnos = $_POST['itemno'];
  $descriptions = $_POST['description'];

  // loop through array
  $number = count($itemnos);
  for ($i = 0; $i < $number; $i++) {
    // store a single item number and description in local variables
    $itno = $itemnos[$i];
    $desc = $descriptions[$i];

    // this is where your insert should be (instead of the echo),
    // insert the single values in $itnm and $desc

    if ($itemnos[$i] <> "") {
      echo "Item: " . $itno . "   Description: " . $desc . "<p>";
    }
    else {
      echo 'Error in row(s): ' . $i . ', <br>' . "\n";  // <-- How can I make this show the Row ID?
    }

  /* Un-Comment for checking posted info

    // Check POST array
    foreach ($_POST as $key => $value) {
      echo '<p>'.$key.'</p>';
      foreach($value as $k => $v) {
        echo $k.'<br/>';
        echo $v;
      }
    }

  */

  }
?>

非常感谢您的帮助!

samimi_it

1 个答案:

答案 0 :(得分:0)

对于对同一问题感兴趣的任何人,这是我设法提出的最终结果。 欢迎提出意见和更正。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org /TR/xhtml1    /DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multiple Adds</title>
</head>
<body>
<?php

 // Get todays date fo day of signup entry
 $today = date("Y.m.d H:i:s");

 // Add one year to date of singup for login validity
 $nextyear = date('Y.m.d H:i:s', strtotime('+1 year'));


 /* 
    // Table to create which is used in this demo
    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `fname` varchar(155) NOT NULL,
      `sname` varchar(155) NOT NULL,
      `lname` varchar(155) NOT NULL,
      `email` varchar(155) NOT NULL,
      `dob` varchar(155) NOT NULL,
      `date_signup` datetime NOT NULL,
      `date_expire` datetime NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
*/

// Set LOCALHOST mysql server connection parameters
define('DB_HOST', 'localhost');     // Change to your own


   define('DB_USER', 'root');           // Change to your own
    define('DB_PASSWORD', '');          // Change to your own
    define('DB_DATABASE', 'test'); // Change to your own

// Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

// Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
    die("Unable to select database");
}

// Create the Form with multiple rows
 echo '<form id="addusers" name="addusers" method="post">';
 echo '<table border="1">';
 echo '<tr><thead>
   <th>RID</th><th>First Name</th>
   <th>Second Name</th>
   <th>Last Name</th>
   <th>eMail</th>
   <th>DOB</th>
   <thead></tr>';

    for($rid=1;$rid <= 10; $rid++)
    {

        echo '<tr>
        <td align="right"><label>'.$rid.'</label></td>
        <td><input id="fname[]" name="fname[]" type="text" size="30"    /></td>
        <td><input id="sname[]" name="sname[]" type="text" size="30" /></td>
        <td><input id="lname[]" name="lname[]" type="text" size="30" /></td>
        <td><input id="email[]" name="email[]" type="text" size="40" /></td>            
        <td><input id="dob[]" name="dob[]" type="text" size="10" /></td>
        </tr>';

    }

 echo '<td colspan="6" align="middle"><input name="submit" id="submit" type="submit" value="Add Users"></td>';
 echo '</table>';
 echo '</form>';

 echo '<hr>';



 // Check for post errors for each field in each row, and prepare error flag and message for display

 $error=false;
 $errormsg="<ul><font color='red'><b><u>Please correct the error(s) in row(s): </font></b></u><br><br>";

    for($x=0;$x < count($_POST['fname']); $x++){        

        if(!$_POST['fname'][$x]){
        $rowNum = $x+1;
        $errormsg.="<li>Row $rowNum: First Name</li>";
        $error=true;
        }

    if(!$_POST['sname'][$x]){
    $rowNum = $x+1;
    $errormsg.="<li>Row $rowNum: Second Name</li>";
    $error=true;
    }

    if(!$_POST['lname'][$x]){
    $rowNum = $x+1;
    $errormsg.="<li>Row $rowNum: Last Name</li>";
    $error=true;
    }

    if(!$_POST['email'][$x]){
    $rowNum = $x+1;
    $errormsg.="<li>Row $rowNum: Email Address</li>";
    $error=true;
    }

    if(!$_POST['dob'][$x]){
    $rowNum = $x+1;
    $errormsg.="<li>Row $rowNum: Date of Birth</li>";
    $error=true;
    }


    }

if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST'){

if($error){

    // Print Errors

            $errormsg.= "<br><font color='red'><b><u>Errors, no data 

posted!</font></b></u></ul><br>"; 
                echo $errormsg;

                echo "<p>Please <a href='javascript:history.back()'><< Go Back</a> and correct!</p>";
}else{ 

    // Print Data submitted and Insert data into DB, but with teration for one time bulk insert of all

    $query = "insert into users (fname,sname,lname,email,dob,date_signup,date_expire) values ";     

    $count = count($_POST['fname']);

    for($x=0;$x < $count; $x++)     
    {

    $fname = $_POST['fname'][$x];
    $sname = $_POST['sname'][$x];
    $lname = $_POST['lname'][$x];
    $dob = $_POST['dob'][$x];
    $email = $_POST['email'][$x];

    echo $fname . $sname . $lname . $dob . $email . '<br>';


                     $query .= "(
                     '$fname', 
                     '$sname',
                     '$lname', 
                     '$email', 
                     '$dob',
                     '$today',
                     '$nextyear')";

                    /* If not last iteration, add a comma and a space */
                    if ($x < ($count - 1)) {
                          $query .= ", ";
                         }

                    $result = mysql_query($query);

            }
                            if(!$result){


die(mysql_error());
                                            @mysql_free_result($result);
                                            } else {



$totalRID = mysql_affected_rows();
                                    $lastRID = mysql_insert_id()-1;
                                    $q = "SELECT LAST_INSERT_ID() FROM users";
                                    $numRowsInerted = mysql_num_rows(mysql_query($q));
                                    echo "Total of <b>" . $totalRID . " </b> rows/records entered into the table!" . "<br>";                                    
                                    echo "Last record number before this bulk insert was: <b>" . $lastRID . 
                                    "</b><br>Last record number after this bulk insert is: <b> " . $numRowsInerted . " </b><br>";


                        }   

    }
}


echo '<hr>';



     // Remaining code hereafter is to get the Table records for display 

      //get the number of total rows
      $query = "SELECT * FROM users";
$result = mysql_query($query);

// Number of records found
$num_record = mysql_num_rows($result);

echo 'Total number of users: ' . $num_record;

echo '<table border="1">';

echo '<tr><thead>
      <th>RID</th><th>First Name</th>
      <th>Second Name</th>
      <th>Last Name</th>
      <th>eMail</th>
      <th>DOB</th>
      <th>Member Signup Date</th>
      <th>Member Renewal Date</th>
      <thead></tr>';

  //here you do your loop like
  while($row=@mysql_fetch_object($result)) {

 echo '<tr>
       <td align="right">'.$row->id.'</td>'.
       '<td>'.$row->fname.'</td>'.
       '<td>'.$row->sname.'</td>'.
       '<td>'.$row->lname.'</td>'.
       '<td>'.$row->email.'</td>'.      
       '<td>'.$row->dob.'</td>'.
       '<td>'.$row->date_signup.'</td>'.
       '<td>'.$row->date_expire.'</td>'.
       '</tr>';
}
echo '</table>';

?>

</body>

</html>