This is weird, and ive never seen this before. Im using post to post values back to the same page for processing. Everything is working fine until I try to use a hidden field to post values. Using the same convention ive used a million times before. The odd thing is that its not posting using the name supplied, its just using hiddenField as the name. Here is the code
<input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" />
And im using this to figure it out
print_r($_POST);
This is the result
[hiddenField] => 6
Now, its posting the value, and its posting the correct value that is put into the hidden field before its submitted, but for some reason that I cant seem to figure out, its not using the name attribute that I set in HTML to identify it. All my other values are using there posted names. Any insight would be greatly appreciated as I do not wish to have to deal with an awkward array of hiddenFields later on.
Edit: Here is the rest of the code for the page (pertinent parts)
<?
if (isset($_POST['Submit']))
{
print "<p>EID: " . $_POST['hiddenField'] . "</p>";
$eid = $_POST['hiddenField'];
$name = $_POST['name'];
$email = $_POST['email'];
$ncount = count($name);
$ecount = count($email);
$hash = uniqid() . "-" . count($name);
if ($ncount == $ecount)
{
$test = true;
for ($i = 0; $i < $ncount; $i++)
{
if ($name[$i] == "" || $email[$i] == "")
{
$test = false;
}
}
if ($test)
{
$tickets[] = array();
for ($i = 0; $i< $ncount; $i++)
{
$unique = false;
while (!$unique)
{
$tickets[$i] = generateCode();
$check_query = "SELECT id FROM ticket WHERE ticket_number='" . $tickets[$i] . "'";
if ($stmt = $mysqli->prepare($check_query))
{
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count == 0)
{
$unique = true;
} else {
print "<p>Not unique</p>";
}
} else {
print "<p>Failed to work database</p>";
}
}
if ($unique == true)
{
$query = "INSERT INTO ticket (`ticket_number`, `event_id`, `name`, `email`,`date_created`, `hash`) VALUES (?,?,?,?,NOW(),?)";
print "<p>Ticket #" . $tickets[$i] . " Event Id: " . $eid . " Name: " . $name[$i] . " Email: " . $email[$i] . " Hash: " . $hash . "</p>";
if ($stmt = $mysqli->prepare($query))
{
$stmt->bind_param('sisss', $tickets[$i], $eid, $name[$i], $email[$i], $hash);
$stmt->execute();
$number = $stmt->affected_rows;
} else {
print "<p>Could not insert into DB because " . $stmt->error . "</p>";
}
}
}
}
}
}
<form action="register.php" method="post">
<table width="896" border="0">
<?
for($i = 0; $i<$_GET['quant']; $i++)
{
?> <tr>
<td><strong>Attendee <? print $z = $i+1; ?></strong></td>
<td> </td>
</tr>
<tr>
<td width="215">Name</td>
<td width="671"><label for="name"></label>
<input type="text" name="name[]" id="name" /></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email[]" id="name2" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<?
}
}
?>
<tr>
<td><input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" /></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>
Related
i have a shopping cart session which completely inserts into the database through a loop, once i make a redirect to the session, it inserts only one product out of the multiple products in the session.
for($i = 0; $i < count($_SESSION['shopping_cart']); $i++){
$title = $_POST['title'][$i];
$quantity = $_POST['quantity'][$i];
$total = $_POST['total'][$i];
$sql = "INSERT INTO orders (title, quantity, total, paid, created_at, updated_at)";
$sql .= " VALUES ( '";
$sql .= $title . "', '";
$sql .= $quantity . "', '";
$sql .= $total . "', '";
$sql .= 0 . "', '";
$sql .= $timestamp . "', '";
$sql .= $timestamp . "')";
$result = $database->query($sql);
if($result){
//success
echo 'yes';
//redirect_to('order_summary.php');
}else{
echo 'no';
//failure
}
}
This is the table below, i am abit confused as to why whenever i make the page redirect, the for loop is not totally inserted in the database, but each time i remove the redirect, it loops completely with all the details into the database.
<table class="table table-striped">
<tr>
<th colspan="7"><h3 class="text-center">Order details</h3></th>
</tr>
<tr class="bg bg-success">
<th>Title</th>
<th>Slug</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th>Actions</th>
</tr>
<?php
if(!empty($_SESSION['shopping_cart']));
$total = 0;
foreach($_SESSION['shopping_cart'] as $key => $product):
?>
<form method="post" action="cart5.php" class="form-horizontal">
<tr>
<td class="text-info"><input type="text" readonly class="form-control" name="title[]" value="<?php echo $product['title']; ?>"/></td>
<td><input type="text" readonly class="form-control" name="price[]" value="N<?php echo $product['price']; ?>"/></td>
<td class="text-center text-info"><input type="text" readonly class="form-control" name="quantity[]" value="<?php echo $product['quantity']; ?>"/></td>
<td><input type="text" readonly class="form-control" name="total[]" value="N<?php echo number_format($product['quantity'] * $product['price'], 2); ?>"/></td>
</tr>
<?php
$total = $total + ($product['quantity'] * $product['price']);
endforeach;
?>
<tr>
<td class="bg bg-success" colspan="7" align="center"><b>SubTotal = N</b><input type="text" readonly multiple class="form-control" name="subTotal[]" value="<?php echo number_format($total, 2); ?>"/></td>
</tr>
<tr>
<td colspan="7">
<?php
if (isset($_SESSION['shopping_cart'])):
if (count($_SESSION['shopping_cart']) > 0):
?>
<input type="submit" name="submit" class="btn btn-success text-right" value="Checkout" />
<?php endif; endif; ?>
</td>
</tr>
</table>
The problem is that you redirect in the loop after the first success...
for($i = 0; $i < count($_SESSION['shopping_cart']); $i++){
// ....
if($result){
//success
echo 'yes';
//redirect_to('order_summary.php');
}else{
echo 'no';
//failure
}
}
What you need to do is redirect only either on failure or when the loop has finished...
for($i = 0; $i < count($_SESSION['shopping_cart']); $i++){
// ....
if(!$result){
echo 'no';
//failure
redirect_to('failed.php');
}
}
redirect_to('order_summary.php');
Or use a flag which flags what to do after the loop...
$success = true;
for($i = 0; $i < count($_SESSION['shopping_cart']); $i++){
// ....
if(!$result){
echo 'no';
//failure
$success = false;
}
}
if ( $success ) {
redirect_to('order_summary.php');
}
else {
redirect_to('failed.php');
}
This is based on the assumption that redirect_to() is outputting the header and automatically calling exit which will stop the script.
All these have the possibility that they will leave an order half inserted, depending on how important that is may dictate if you want to wrap it all in a transaction or not.
Your logic is telling it to redirect after any successful insert. Hence, first run through the loop it works and it redirects.
Also, you can't send header()s after starting any output to the client - the echo 'yes' may give you problems. I'd change it to set/track a boolean and after the loop is complete do something.
for($i = 0; $i < count($_SESSION['shopping_cart']); $i++){
$title = $_POST['title'][$i];
$quantity = $_POST['quantity'][$i];
$total = $_POST['total'][$i];
$success=true; // assume it works
$sql = "INSERT INTO orders (title, quantity, total, paid, created_at, updated_at)";
$sql .= " VALUES ( '";
$sql .= $title . "', '";
$sql .= $quantity . "', '";
$sql .= $total . "', '";
$sql .= 0 . "', '";
$sql .= $timestamp . "', '";
$sql .= $timestamp . "')";
$result = $database->query($sql);
if(!$result){
// failure do something like trapping the sql error,
// or recording a message in an array
$success=false;
}
}
if($success){
// it all worked!
// do your redirect here
}else{
// something failed
// do your error output, warning to user, whatever here
}
This is my code, where a user can add dynamic rows by clicking add more link.
But when I print
print_r($this->input->post('name1'));
in controller, it prints only first value but I want all values of array.
<form action="test.php" method="post">
<table rules="all" style="background:#fff;">
<tr>
<td style="font-size:14px;" >Name</td>
<td style="font-size:14px;">Email</td>
<td style="font-size:14px;">Mobile</td>
<td><span style="font:normal 12px agency, arial; color:blue; text-decoration:underline; cursor:pointer;" onclick="addMoreRows(this.form);">Add More</span>
</td>
</tr>
<tr id="rowId">
<td><input name="name1[]" type="text" value="" size="17%"/></td>
<td><input name="age1[]" type="text" value="" /></td>
<td><input name="relation1[]" type="text" value="" /></td>
</tr>
</table>
<div id="addedRows"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var rowCount = 1;
function addMoreRows(frm) {
rowCount ++;
var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="name1[]" type="text" size="17%" maxlength="120" /></td><td><input name="age1[]" type="text" maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="relation1[]" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> Delete</p>';
jQuery('#addedRows').append(recRow);
}
function removeRow(removeNum) {
jQuery('#rowCount'+removeNum).remove();
}
</script>
</form>
Try saving it to another variable and printing it like this:
$name1 = $this->input->post('name1');
print_r($name1);
You can loop through all the POST item, so you print out all the POST values. Also, I suggest incremented the 'name' atttribute as well, so you will have name1, name2, name 3 etc, or just remove the number because you are using an array.
If you want to increment the 'name' attribute
To loop:
$counter = 0;
foreach ($this->input->post('name1') as $key => $value)
{
$counter++;
// $value = name1
echo $this->input->post('age". $counter ."');
echo $this->input->post('relation". $counter ."');
}
With array
To loop:
foreach ($this->input->post('name1') as $key => $value)
{
echo $value;
$this->input->post('age1');
$this->input->post('relation1');
}
I havent tested it myself
Change your view page:
put <?php echo form_open_multipart('test/add_member'); ?> instead of
<form action="test.php" method="post">
In Controller: Dynamic input array data can handle as follows, this may help you..thanks!
public function add_member()
{
if (!$this->ion_auth->logged_in()) {
redirect('auth/login');
}
$itemCount = count($this->input->post('name'));
$itemValues=0;
$query = "INSERT INTO You_table_name(name, age, relation) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
$name = $this->input->post('name');
$age = $this->input->post('age');
$relation = $this->input->post('relation');
if(!empty($name[$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $name[$i] . "', '" . $age[$i] . "', '" . $relation[$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
if (!$this->db->query($sql)) {
// echo "FALSE";
}else {
// echo "TRUE";
}
}
}
I'm trying to insert multiple row, when I'm insert data it take extra two null row. but why it is happening...Please some one help me to solve this problem.........
this is my form page
<?php
require_once 'Insert_class.php';
$obj_Insert_class=new Insert_class();
$new= $obj_Insert_class->employee_select_data();
$massage='';
if(isset($_POST['btn'])){
$massage=$obj_Insert_class->time_add();
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<h2>Multiple Insert</h2>
<?php echo $massage; ?>
<form action="" method="post">
<table width='30%'>
<tr>
<td><u><b>EMPLOYEE NAME</b></u></td>
</tr>
<?php
while ($row = mysqli_fetch_assoc($new)) {
?>
<tr>
<td><input name="eid[]" class="case" type="text" value="<?php echo $row['eid']; ?>" /></td>
<td><input name="employee_name[]" class="case" type="text" value="<?php echo $row['employee_name'] ?>"/></td>
<td><input name="status[]" class="case" type="text" value="1"/></td>
<td><input name="first[]" id="first" type="number"/></td>
<td><input name="second[]" id="second" type="number"/></td>
</tr>
<?php } ?>
<tr>
<td></td>
<td><input type="submit" name="btn" value="Submit" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>
this is my insert class page
<?php
require './connect.php';
class Insert_class extends Connect {
protected $link;
public function __construct() {
$this->link = $this->conntection();
}
public function time_add() {
$i = 0;
foreach ($_POST as $val) {
error_reporting(0);
$eid = $_POST['eid'][$i];
$name = $_POST['employee_name'][$i];
$status = $_POST['status'][$i];
$first = $_POST['first'][$i];
$second = $_POST['second'][$i];
$new_add = $first + $second;
$SQL = "INSERT INTO time(eid,name,status,first,seconc,new_add)VALUES('$eid','$name','$status','$first','$second','$new_add')";
if (mysqli_query($this->link, $SQL)) {
$massage = 'DATA Susseccfully inserted';
} else {
die('Select query problem' . mysqli_error($this->link));
}
$i++;
}
return $massage;
}
public function employee_select_data() {
$SQL = "SELECT * FROM employee";
if (mysqli_query($this->link, $SQL)) {
$result = mysqli_query($this->link, $SQL);
return $result;
} else {
die('Select query problem' . mysqli_error($this->link));
}
}
}
Your code contains this loop.
$i = 0;
foreach ($_POST as $val) { /* wrong! */
/* do the insert */
$i ++;
}
This makes no sense. The $_POST is an array of values posted from your form. This loop iterates over each value in that array. That's too many iterations.
Instead, you need to figure out the size of the arrays in your form-field elements of $_POST. Try something like this:
$some_field = $_POST['eid'];
$i = 0;
foreach ($some_field as $junk) {
/* do the insert */
$i++;
}
<form action="book.php" method="post">
<table>
<thead>
<tr>
<td>FlightID</td>
<td>From</td>
<td>Destination</td>
</tr>
</thead>
<tbody>
<tr>
<td name="flightID" value="1">1</td>
<td name="From" value="Sydney">Sydney</td>
<td name="Destination" value="Bali">Bali</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</tr>
<tr>
<td name="flightID" value="2">2</td>
<td name="From" value="London">London</td>
<td name="Destination" value="HongKong">Hong Kong</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</tr>
</tbody>
</table>
</form>
I created a table like this. At the end of each row, it has a book button.
What I am trying to do is when the user clicked the button, the selected row data(ID,From,Des) will pass to the 'book.php', then the PHP file will do the rest of the job.
But I tried to catch the value using $_POST['name'] in 'book.php', like this
<?php
if(isset($_POST['booking'])){
$ID = $_POST['flightID'];
$From = $_POST['From'];
$To = $_POST['Destination'];
}
?>
It shows all of those values are undefined. Any help would be appreciated.
The problem is that the values in <td> cannot be passed from the form to your PHP file by themselves. You could use hidden inputs for this. Additionally, each row in the table should be its own form to assure that all data is not submitted at the same time.
Try this:
<table>
<thead>
<tr>
<td>FlightID</td>
<td>From</td>
<td>Destination</td>
</tr>
</thead>
<tbody>
<tr>
<form action="book.php" method="post">
<td><input type="hidden" name="flightID" value="1">1</td>
<td><input type="hidden" name="From" value="Sydney">Sydney</td>
<td><input type="hidden" name="Destination" value="Bali">Bali</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</form>
</tr>
<tr>
<form action="book.php" method="post">
<td><input type="hidden" name="flightID" value="2">2</td>
<td><input type="hidden" name="From" value="London">London</td>
<td><input type="hidden" name="Destination" value="HongKong">Hong Kong</td>
<td class="tdBook"><button class="btnBook" type=submit name="booking"> Book </button>
</form>
</tr>
</tbody>
i have the same problem as yours and tried to create an answer so i came up with this code to indicate each row in an HTML table with a special name using loops, i can now take the specified row and do as much PHP operations as i can with it without disturbing the table as a whole and it was well synchronized with my database, hope it helps!
and btw the whole "marking each row with a special name" code is in usersTable.php
users.sql
create table users(
id int,
username varchar(50),
password varchar(50)
);
users.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "wdl2hw4db";
$conn = mysqli_connect($host, $username, $password, $database);
if (mysqli_connect_errno()){
die("can't connect to the Database" . mysqli_connect_errno());
}else{
echo "Database is connected" . "<br>";
}
if (isset($_POST['insert'])){
$idN1= $_POST['id'];
$usernameN1 = $_POST['username'];
$passwordN1 = $_POST['password'];
$query = "insert into users(id, username, pass) values ('".$idN1."' , '".$usernameN1."' , '".$passwordN1."' )";
$result = mysqli_query($conn, $query);
}else if (isset($_POST['update'])){
$idN2 = $_POST['id'];
$usernameN2 = $_POST['username'];
$passwordN2 = $_POST['password'];
$query = "update users set pass = '". $passwordN2 ."'where id = " . $idN2;
$result = mysqli_query($conn, $query);
}else if (isset($_POST['Display'])){
header('Location: usersTable.php');
}
echo "<br>";
?>
<form method="post">
ID: <input type="text" name="id" ><br><br>
username: <input type="text" name="username" ><br><br>
password: <input type="password" name="password" ><br><br>
<input type="submit" name="insert" value="insert">
<input type="submit" name="Display" value="Display">
</form>
userTable.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "wdl2hw4db";
$conn = mysqli_connect($host, $username, $password, $database);
$query = "select * from users";
$result = mysqli_query($conn, $query);
echo "<table border=\"6px\"><thead><tr><th>ID</th><th>username</th><th>password</th><th>Delete</th><th>Update</th></tr></thead>";
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><form method='post'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['pass'] . "</td><td><input type='submit' name='Delete" . $i . "' value='Delete'></td><td><input type='submit' name='Update" . $i . "' value='Update'><input type='text' name='UpdateText" . $i . "' placeholder='insert new password here'></td></form></tr>";
$i++;
}
echo "</table>";
$i = 1;
$result2 = mysqli_query($conn, $query);
while ($row2 = mysqli_fetch_assoc($result2)) {
if (isset($_POST['Delete' . $i])) {
$usernameN4 = $row2['username'];
$query2 = "delete from users where username ='" . $usernameN4 . "'";
$result2 = mysqli_query($conn, $query2);
header("Refresh:0");
break;
}
$i++;
};
$i = 1;
$result3 = mysqli_query($conn, $query);
while ($row3 = mysqli_fetch_assoc($result3)) {
if (isset($_POST['Update' . $i]) && $_POST['UpdateText' . $i] != null ) {
$id4 = $row3['id'];
$Utext = $_POST['UpdateText' . $i];
$query3 = "update users set pass ='" . $Utext . "' where id = " . $id4;
$result3 = mysqli_query($conn, $query3);
header("Refresh:0");
break;
}
$i++;
};
mysqli_free_result($result);
I have two PHP files:
1) simplearraypost.php (containing the form)
2) echoarraypost.php (the validation of the form)
The form have 3 columns, which are
1) Row Number
2) Item Number
3) Description
Now, if posted, need validation per each cell of rows & columns!
Codes for both pasted here separately.
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;
}
}
*/
}
?>
Your help is very much appreciated!
samimi_it
For anyone interested in the same issue,here is the final result I managed to come up with.
Comments and corrections are most welcome.
<!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>