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
}
Related
<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'm trying to work on an inventory system where users may view their inventory and update quantity with the value that input by user only and rest remains the same from database. But its not working please help me find where I did wrong. It will echo the success message but the database isn't updated.
<form name="form" method="post">
<table width="70%" border="5" align="center"><tr>
<th scope="row">SKU</th>
<th scope="row">Item Description</th>
<th scope="row">Current Qunatity</th>
<th scope="row">Update Quantity</th>
<th scope="row">Unit Price</th>
</tr>
<tr>
<th scope="row">
<?php
include('connect.php');
$result = mysqli_query("SELECT * FROM products")
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )) {
echo "<tr>";
echo '<td><a name="sku[]">'.$row['sku_id'].'</a></td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.$row['quantity'].'</td>';
echo '<td><input name="qty[]" /></td>';
echo '<td>'.$row['unit_price'].'</td>';
echo "</tr>";
}
?>
</table>
<input style="float:right" name="update" type="submit" id="update" value="Update"/>
</form>
<?php
if(isset($_POST['update']))
{
$qty = $_POST['qty'];
$sku = $_POST['sku'];
foreach($qty as $key => $value)
{
if(empty($value))
{
continue;
}
else
{
$sql = "UPDATE products SET quantity ='".$value."' WHERE sku_id = '".$sku[$key]."'";
mysql_query($sql);
}
}
$retval = mysqli_query($sql);
if(! $retval)
{
die('Could not update data: '. mysql_error());
}
echo 'Update data successfully!';
}
?>
You are using mysql_query here:
$sql = "UPDATE products SET quantity ='".$value."' WHERE sku_id = '".$sku[$key]."'";
mysql_query($sql);
Instead of mysqli_query:
$sql = "UPDATE products SET quantity ='".$value."' WHERE sku_id = '".$sku[$key]."'";
mysqli_query($sql);
In addition, you're using mysql_error here as well:
die('Could not update data: '. mysql_error());
P.S. Don't forget to escape any user input you are using in a database query! Though ideally you should use something like PDO or MySQLi prepared statements
This should be a full answer for you (with mysqli update):
<form name="form" method="post">
<table width="70%" border="5" align="center">
<tr>
<th scope="row">SKU</th>
<th scope="row">Item Description</th>
<th scope="row">Quantity</th>
<th scope="row">Unit Price</th>
</tr>
<?php
include('connect.php');
$result = mysqli_query("SELECT * FROM products")
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )) {
echo "<tr>";
echo '<td>'.htmlspecialchars($row['sku_id']).'</td>';
echo '<td>'.htmlspecialchars($row['description']).'</td>';
echo '<td><input name="qty['.htmlspecialchars($row['sku_id']).']" value="'.htmlspecialchars($row['quantity']).'"/></td>';
echo '<td><input name="price['.htmlspecialchars($row['sku_id']).']" value="'.htmlspecialchars($row['unit_price']).'"/></td>';
echo "</tr>";
}
?>
</table>
<input style="float:right" name="update" type="submit" id="update" value="Update"/>
</form>
<?php
if(isset($_POST['update']))
{
$qty = $_POST['qty'];
$price = $_POST['price'];
$stmt = $mysqli->stmt_init(); // <- mysqli class way of doing this
$stmt->prepare("UPDATE products SET quantity = ?, unit_price = ? WHERE sku_id = ?");
foreach($qty as $key => $value)
{
$data = array($qty[$key], $price[$key], $key);
$stmt->execute($sql, $data);
}
echo 'Update data successfully!';
}
?>
For testing purposes the processing of post can be changed to:
if(isset($_POST['update']))
{
$qty = $_POST['qty'];
$price = $_POST['price'];
//$stmt = $mysqli->stmt_init(); // <- mysqli class way of doing this
//$stmt->prepare("UPDATE products SET quantity = ?, unit_price = ? WHERE sku_id = ?");
foreach($qty as $key => $value)
{
echo "UPDATE products SET quantity = ".$qty[$key].", unit_price = ".$price[$key]." WHERE sku_id = " . $key . "<br/>\n";
//$data = array($qty[$key], $price[$key], $key);
//$stmt->execute($sql, $data);
}
echo 'Update data successfully!';
}
If you do a var_dump($_POST); you will see that your inputs have no values.
You need to specify the value on your form.
I would prefer to do this instead though:
echo '<input name="sku['.$row['sku_id'].']" value="'.$row['quantity'].'" />';
Then you can cycle through $_POST['sku'] and use the Key as the sku_id and the Value as the new value (quantity), to be updated
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>
I have two arrays the selected and questiondesc, I want to update it to the database but My code doesnt seem to work. Is it possible to do nested for each?
<?php do { ?>
<tr>
<th width="170" scope="col">
<input type="checkbox" name="selected[]"
value="<?php echo $row_Recordset1['question_id'];?>"/>
Description:
</th>
<td colspan="2" scope="col">old:
<?php echo $row_Recordset1['question_description']; ?>
new:<input name="questiondesc[]" type="text" size="50"/>/td>
<td width="549" colspan="2" scope="col">
<div align="left">
</td>
</tr>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
if (isset($_POST['selected'])) {
$selected = $_POST['selected'];
$question = $_POST['questiondesc'];
foreach ($selected as $enable) {
mysql_query("
UPDATE exam_questions
SET question_description = '$question'
WHERE question_id = '$selected'
") or die(mysql_error());
}
}
You could use a for instead and make sure to properly sanitize your data:
for ($i = 0; $i < sizeof($selected); $i++)
{
$sql = sprintf("UPDATE exam_questions
SET question_description = '%s'
WHERE question_id = '%s'",
mysql_real_escape_string($question[$i]),
mysql_real_escape_string($selected[$i]));
mysql_query($sql)or die(mysql_error());
}
Keep in mind that the above assumes that questions and selections are ordered the same.
Change this line:
mysql_query("UPDATE exam_questions
SET question_description = '$question'
WHERE question_id = '$enable' ")or die(mysql_error());
<?
$i =0;
while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)):
?>
<tr><th width="170" scope="col"><input type="checkbox" name="selected[]" value="<?php echo $row_Recordset1['question_id']; ?>" />
Description:</th><td colspan="2" scope="col">old:
<?php echo $row_Recordset1['question_description']; ?>
new:<input name="questiondesc_<?=$i?>" type="text" size="50" />/td>
<td width="549" colspan="2" scope="col"><div align="left"></td>
</tr>
<?
$i ++;
endwhile;
?>
if(isset($_POST['selected'])){
$selected = $_POST['selected'];
foreach($selected as $id){
$key = 'questiondesc_' . $id;
$question = $_POST[$key];
$sql = "UPDATE exam_questions SET question_description = '" . $question . "' WHERE question_id = '" . $id . "'";
mysql_query($sql)or die(mysql_error());
}
}
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>