Rows and Columns validation of an Array after form submitted - php

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>

Related

Redirect successfully after loop is completed

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
}

how to insert html table values in mysql table

Using following code I have fetched Student ID and Student name from mysql table in html table. In third column which is Obtained Marks I am getting student marks through input box. Now I want to insert all three columns (Student ID, Student Name and Obtained Marks) in new table which is testrecord.
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
$SelectClass = $_POST ['selectclass'];
$sql= "SELECT * FROM students WHERE class = '$SelectClass'";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
mysqli_close($connection);
?>
<body>
<div class="container">
<form class="well form-horizontal" action="insert_marks.php" method="post">
<h1><strong>Please enter marks of each student for subject</strong></h1>
<form action="" method="post">
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Sr.No.</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query)) {
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student_id" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student_name" value='.$row['student_name'].'>
<td>
<div class="search-block clearfix">
<input name="obtmarks" placeholder="" type="number">
</div>
</td>
</tr>';
$total += $row['stu_id'];
$no++;
}
?>
</tbody>
</table>
<button type="submit" class="btn btn-warning" value="insert" align="right">Update<span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</body>
</html>
insert_marks.php:
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
//***********Form Submit Goes Here***********//
while
if($_POST) {
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
$student_marks = $_POST['obtmarks'];
$sql= "INSERT INTO testrecord (student_id,student_name,obtained_marks) VALUES ('$student_id','$student_name','$student_marks')";
if (mysqli_query($connection, $sql)) {
echo "Marks added successfully.";
echo "<br>";
echo "<br>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
mysqli_close($connection);
?>
</body>
</html>
There are 20 entries in table. After inserting marks for each student in text box, above coding inserts only last record in mysql table 'testrecord'. Can you please correct the insert_marks.php code.
Change on Html table tbody part:
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query)) {
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student_id[]" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student_name[]" value='.$row['student_name'].'>
<td>
<div class="search-block clearfix">
<input name="obtmarks[]" placeholder="" type="number">
</div>
</td>
</tr>';
$total += $row['stu_id'];
$no++;
}
?>
</tbody>
in insert_marks.php change while part:
//***********Form Submit Goes Here***********//
while
if($_POST) {
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
$student_marks = $_POST['obtmarks'];
for($i = 0; $i < count($student_id); $i++){
$sql= "INSERT INTO testrecord (student_id,student_name,obtained_marks) VALUES ('$student_id[$i]','$student_name[$i]','$student_marks[$i]')";
if (mysqli_query($connection, $sql)) {
echo "Marks added successfully.";
echo "<br>";
echo "<br>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
}
Try this
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
$SelectClass = $_POST ['selectclass'];
$sql= "SELECT * FROM students WHERE class = '$SelectClass'";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
mysqli_close($connection);
?>
<body>
<div class="container">
<form class="well form-horizontal" action="insert_marks.php" method="post">
<h1><strong>Please enter marks of each student for subject</strong></h1>
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Sr.No.</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query)) {
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student['.$no.'][student_id]" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student['.$no.'][student_name]" value='.$row['student_name'].'>
<td>
<div class="search-block clearfix">
<input name="student['.$no.'][obtmarks]" placeholder="" type="number">
</div>
</td>
</tr>';
$total += $row['stu_id'];
$no++;
}
?>
</tbody>
</table>
<button type="submit" class="btn btn-warning" value="insert" align="right">Update<span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</body>
</html>
insert_marks.php:
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
//***********Form Submit Goes Here***********//
if(isset($_POST['student']) && !empty($_POST['student'])) {
$queryStr = '';
$cnt = count($_POST['student']);
foreach ($_POST['student'] as $key => $student) {
$queryStr .= "('".$student['student_id']."','".$student['student_name']."','".$student['obtmarks']."') ";
if (($key + 1) != $cnt) {
$queryStr .= " , ";
}
}
if ($queryStr != '') {
$sql= "INSERT INTO testrecord (student_id,student_name,obtained_marks) VALUES $queryStr";
if (mysqli_query($connection, $sql)) {
echo "Marks added successfully.";
echo "<br>";
echo "<br>";
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
mysqli_close($connection);
?>
</body>
</html>

Edit MySQL Row PHP

I'm trying to edit and update a row using PHP.
Here is the code:
index.php
<!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">
<div class="header">
<?php include 'header.php';?>
</div>
<center>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include_once('../connection.php');
// get results from database
$query = "SELECT EmployeeName, DOB, Age, StreetAddress, City, State, ZipCode,
Email, HomePhone, Wireless, JobTitle, id, HomeDept, Manager FROM headcount ORDER BY `headcount`.`EmployeeName` ASC";
$response = #mysqli_query($dbc, $query);
// display data in table
echo "<p><b>View All</b> | <a href='../employees/rides.php'>Rides</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Employee Name</th> <th>Home Department</th> <th>Job Title</th> <th>Edit</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysqli_fetch_array($response)){
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['EmployeeName'] . '</td>';
echo '<td>' . $row['HomeDept'] . '</td>';
echo '<td>' . $row['JobTitle'] . '</td>';
echo '<td>Edit</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
</center>
edit.php
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db("hwss") or die(mysql_error());
$UID = (int)$_GET['ID'];
$query = mysql_query("SELECT * FROM headcount WHERE id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$EmployeeName = $row['EmployeeName'];
$DOB = $row['DOB'];
$Age = $row['Age'];
$email = $row['email'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
email: <input type="text" name="ud_email" value="<?=$email;?>"><br>
Name: <input type="text" name="ud_EmployeeName" value="<?=$EmployeeName?>"><br>
DOB: <input type="text" name="ud_dob" value="<?=$DOB?>"><br>
Age: <input type="text" name="ud_Age" value="<?=$Age?>"><br>
<input type="Submit">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I click edit it says "No entry found" with the back link on each ID url. I understand that I don't have any Update code yet. I'm simply just trying to get it to display the data before adding the rest.
Error Message
Notice: Undefined index: ID in C:\xampp\htdocs\Scheduling\Employees\edit.php on line 5
No entry found. Go back
Use: $_GET['id']
$UID = (int)$_GET['id'];
instead of
$UID = (int)$_GET['ID'];

How to loop each input in each row and insert it in the database?

I have a form with undefined number of input.
.
When I click submit, each row should be inserted in the database with different IDs. (ex. the 1st row should have id# 100, 2nd row-id# 101) My problem is I don't know how to loop each input in each row.
HTML code
<form action="addnewhousehold.php" method="POST">
<table class="table table-striped" id="table-form">
<thead>
<tr>
<th>Firstname</th>
<th>Middlename</th>
<th>Lastname</th>
<th>Extension name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstname[]" id="firstname"></td>
<td><input type="text" name="middlename[]" id="middlename"></td>
<td><input type="text" name="lastname[]" id="lastname"></td>
<td><input type="text" name="extension_name[]" id="extension_name"></td>
</tr>
</tbody>
</table>
<a id="moreinput"><span class="fa fa-plus fa-fw"></span> Add more input</a>
</form>
JS code (Source: http://jsfiddle.net/2HGdv/13/)
$(document).ready(function(){
$("#moreinput").on('click', function(e){
e.preventDefault();
$("#table-form").each(function(){
var td = '<tr>';
$.each($('tr:last td', this), function(){
td += '<td>' + $(this).html() + '</td>';
});
td += '</tr>';
$(this).append(td);
});
});
});
PHP code
<?php
require 'connectdb.php';
foreach ($_POST['firstname'] as $fname) {
// I DON'T KNOW haha
}
?>
If you are posting only your form fields you can do this:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
This will iterate through any parameter you have in your POST request.
<?php
//// set conecction DB
//$servername = "localhost";
//$username = "username";
//$password = "password";
//$dbname = "myDB";
//// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
//// Check connection
//if ($conn->connect_error) {
// die("Connection failed: " . $conn->connect_error);
//}
require 'connectdb.php';
$sql = "INSERT INTO Table_Name (`firstname`, `middlename`, `lastname`, `extension_name`) VALUES ";
foreach ($_POST['firstname'] as $kay=>$value) {
// $sql .= '' | $sql = $sql . '';
$sql .= "('{$value}','{$_POST['middlename'][$kay]}','{$_POST['lastname'][$kay]}','{$_POST['extension_name'][$kay]}',),";
}
// remove last `,` into query;
$sql = rtrim($sql,',');
$countRow = count($_POST['firstname']);
// execute query $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "{$countRow} record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// close DB conection
$conn->close();
?>

HiddenField posting value without name

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>

Categories