Multiple insertion with same input name in php - php

thank you for your answer meanwhile i got this code for inserting the multiple data, and it really works but my problem is it adds the fisrt column then after finished then it executes the second column i want them to excecute insert f1 then f2 then f1 then f2 again:
just imagine i have 4 input with same name f1 and f2
Inserting multiple entries into table from the same form please refer on this post

Your are missing names in all of your form fields
/*PHP code where the form submit, and repeat the same for other fields like descriptionField*/
<?php
for($i = 0; $i <= count ( $_POST ['dateField'] ); $i ++) {
// Do what ever you want with data
var_dump ( $_POST ['dateField'] [$i] );
}
?>
HTML Code, names added
<tr class="item-row">
<td class="item-name"><div class="delete-wpr">
<textarea>Date</textarea>
<a class="delete" href="javascript:;" title="Remove row">X</a>
</div></td>
<td class="description"><textarea name="descritpionField[]">Description</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="asd">0</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="qty">0</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="cost">0</textarea></td>
<td style="text-align: center;"><span class="price">0</span></td>
</tr>

If i understand correctly
If this fields in form, then set 'name' attr to fields like name="user[]"
When u'll submit the form, all values of "user[]" fields will in array. Just do print_r() and you will see, what i try to explain
Also u can do it in javascript. . .
Just grab all values in array. . .
User "Noor" already post example for you

Please try this code,
<?php
echo "<pre>";
if(isset($_POST['submit'])){
print_r($_POST['data']);//RESULT WILL GET AN ARRAY
}
?>
<form action="" method="post">
<table>
<?php
//$items = // DATA FROM DB
//$items_count = count($items);
$items_count = 5;
for($i=0;$i<$items_count;$i++) {
?>
<tr class="item-row-<?php echo $i;?>">
<td class="item-name"><div class="delete-wpr"><textarea name="data[<?php echo $i;?>]['date']">Date</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea name="data[<?php echo $i;?>]['description']">Description</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['age']" style="text-align:center;" class="asd">0</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['dob']" style="text-align:center;" class="qty">0</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['status']" style="text-align:center;" class="cost">0</textarea></td>
<td style="text-align:center;" ><span class="price">0</span></td>
</tr>
<?php } ?>
<table>
<input type="submit" class="button" name="submit" value="submit" />
</form>

Answer fo the post (Trouble with $_POST [duplicate])
I don't know if I understand your concern.
I think you are trying to create a quiz. And so the user must validate several attempts. your problem is that you can not accumulate the different answers following a table. so here is a solution.
<?php
$good_answers = array(
"easy1" => array("4","3","5","2","6","9","7","8","1" ),
"easy2" => array("6","8","2","5","7","1","4","9","3" ),
"easy3" => array("1","9","7","8","3","4","5","6","2" ),
"easy4" => array("8","2","6","1","9","5","3","4","7" ),
"easy5" => array("3","7","4","6","8","2","9","1","5" ),
"easy6" => array("9","5","1","7","4","3","6","2","8" ),
"easy7" => array("5","1","9","3","2","6","8","7","4" ),
"easy8" => array("2","4","8","9","5","7","1","3","6" ),
"easy9" => array("7","6","3","4","1","8","2","5","9" )
);
if(isset($_POST['row'])){
$easy = false;
$client_responses = $_POST['row']; // EX: [" "," "," " ,"2","6"," " ,"7"," " ,"1"]
$old = json_decode($_POST['old']);
$old[] = $client_responses;
// Or make array_push($old,$client_responses); if you prefere
foreach ($good_answers as $easy => $responses) {
if($client_responses === $responses){
$easy = $responses;
break;
}
}
// generating table for HTML of client responses
echo '<table>';
// saving old responses
echo '<input type="hidden" value="'. json_encode($old) .'" name="old">';
foreach ($old as $number => $row) {
echo '<tr id="row'. $number .'">';
for ($i=0; $i < count($row); $i++) {
echo '<td class="cellTop">';
echo '<input type="text" maxlength="1" name="row" value="'. $row[$i].'"/>';
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
}

Related

Forms & Posting - Multiple Data

So I was looking at some other posts on this site and came across the code below (EDIT of my code) which works perfectly apart from when I submit I get an error code of: Notice: Undefined index: id in /customers/0/2/e/richardbrown.name/httpd.www/debt/payment_process.php on line 17 for each result.
<form method="post" action="payment_process.php">
<table border="0">';
$stmt = $db->query("SELECT * FROM debt_accounts LEFT JOIN debt_companies ON accounts_company=companies_id WHERE accounts_amount > 0 ORDER BY accounts_company ASC");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo'<tr>
<td width="200" align="left"><input type="text" name="payment[][id]" value="'.$row['accounts_id'].'" /></td>
<td width="100" align="right"><input type="text" name="payment[][amount]" value="25.00" /></td>
</tr>';
}
echo'</table><br /> <br /><input type="submit" /></form>
if ( isset( $_POST['payment'] ) )
{
echo '<table>';
foreach ( $_POST['payment'] as $diam )
{
echo '<tr>';
echo ' <td>', $diam['id'], '</td>';
echo ' <td>', $diam['amount'], '</td>';
echo '</tr>';
}
echo '</table>';
}
Change this line from your form element:
name="payment_amount"
to be an array:
name="payment_amount[]"
Then, modify your foreach to read as:
foreach ($_POST['payment_amount'] as $value) {
echo $value . "<br>";
}
You were using the wrong POST array => name="payment_id[]"
To add them all up, should you want to do that, use:
foreach ($_POST['payment_amount'] as $value) {
echo $value . "<br>";
$total += $value;
}
echo $total;
or
$total = array_sum($_POST['payment_amount']);
your solution is :
name="payment_id[]" in your form
and server side (payment_process.php)
you use a foreach loop with the $_POST['payment_id'][].

PHP Variable changes its own value on equal loops

I have a variable putting out the coordinates of a address. I am printing the coordinates before the name to test at the moment. On odd number loops (it is in a foreach loop) it works fine, putting the variable in the data-latLng attribute. While on Even number loops it gives out different values - not coordinates. values like: 2 and ..
Here is what I mean:
An odd numbered loop would print this out:
Meanwhile on an even loop number, the data-latLng attribute puts out different values:
Here is the code:
$area_lat_long = isset($area_lat_long[$mapCounter])?$area_lat_long[$mapCounter]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;
The PHP code runs above the table code, the code above gives the line of the coordinates and then the area.
As you can see, the $area_lat_long gives coordinates before every area, but when using the EXACT same variable for the data-latLng it changes on even loops?
Edit
To the guys who wanted the whole loop in the comments:
foreach ($streetAdd as $key){
print_r($area_lat_long);
//LAT LONG
$area_lat_long = isset($area_lat_long[$count])?$area_lat_long[$count]:"-26.2041028, 28.047305100000017";
echo $area_lat_long;
echo '<strong>area: '. $streetAdd[$count] .' <a class="glyphicon glyphicon-new-window" type="button" data-toggle="modal" data-target="#mapModal" data-latLng="'. $area_lat_long .'" style="cursor:pointer;"></a><br>';
$mapCounter++;?>
<input type="hidden" id="street_address" name="street_address[<?php echo $count; ?>]" value="<?php echo $streetAdd[$count];?>">
<table class="table table-striped">
<thead>
<tr>
<th>Media Type</th>
<th>Quantity Required</th>
<th>Average Asset Price</th>
<th><!-- Remaining Total --></th>
<th>More Options</th>
</tr>
</thead>
<tbody class="assetCounter">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
$j = 0;
$total_used = 0;
$total_bal = isset($budget)?$budget:0;
$qty = 1;
$i = 0;
foreach ($my_categories as $key) { //loop thru chosen media types
foreach ((array)$key as $data) {
// print_r($data);
//check valid description
$j++;
$data_description = isset($data->mec_description)?$data->mec_description:'';
$latitude_longitude = explode(",",$area_lat_long); //print_r($latitude_longitude);
$latitude = $latitude_longitude[0];
$longitude = isset($latitude_longitude[1])?$latitude_longitude[1]:$latitude;
//pricing
$min_price = isset($data->asg_min_price)?$data->asg_min_price:0;
$max_price = isset($data->asg_max_price)?$data->asg_max_price:0;
$average_p = ($min_price + $max_price)/2;
$total_used += $average_p;
$total_bal -= $average_p;
if($total_bal < 0){
$total_bal = 0;
}
if($average_p == 0){
$title = "Pricing information not yet available from Media Owners";
} else {
$title = "NOTE: These are just estimates/guidelines, latest pricing information will be received from Media Owners quotations";
}
?>
<tr class="asset_<? echo $counterForAsset; ?>">
<td><?php
echo strtoupper($mec_stuff[$i]);
?>
<input type="hidden" id="media_category" name="mec_id[]" value="<?php
foreach($mec_stuff as $ms) {
echo $ms . ',';
}
?>">
<input type="hidden" id="media_category" name="media_category[]" value="<?php echo $data_description; ?>"></input></td>
<td><input type="text" class="form-control q_asset_<? echo $counterForAsset; ?> med_quantity" name="med_quantity[]" id="med_quantity" placeholder="Quantity Required" value="1"/></td>
<td><input type="text" readonly="true" name="avg_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control avg_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>" title="<?php echo $title;?>"/></td>
<!-- <td><input type="text" readonly="true" name="avg_total[]" id="avg_total--><?php //echo $j; ?><!--" class="form-control asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--" title="--><?php //echo $title;?><!--"/></td>-->
<td><input type="text" readonly="true" name="rem_total[]" id="asset_<? echo $counterForAsset; ?>" class="form-control rem_asset_<? echo $counterForAsset; ?>" value="<?php echo number_format($total_bal,2); ?>"/></td>
<!-- <td><input type="text" readonly="true" name="rem_total[]" id="rem_total--><?php //echo $j; ?><!--" class="form-control --><?// echo $i; ?><!-- asset_--><?// echo $i; ?><!--" value="--><?php //echo number_format($total_bal,2); ?><!--"/></td>-->
<td><?php echo "<a class='js-fire-modal btn btn-info' type='button' data-toggle='modal' data-mecid='$mec_stuff[$i]' href='#' name='size_button' onclick=\"sizeModal2(1, $j, '$latitude','$longitude','$description')\">>>></a>";?></td>
</tr>
<tr>
<td></td>
<td colspan="4" id="<?php echo $j; ?>"></td>
</tr>
<?php $i ++; $counterForAsset++; }
}?>
<tr>
<td> </td>
<td> <input type="hidden" id="hidSubtotal<?php echo $j;?>" value="<?php echo number_format($total_used,2); ?>"></td>
<td> Subtotal</td>
<td> <span id="lblSubtotal<?php echo $j; ?>"><?php echo number_format($total_used,2); ?></span> </td>
</tr>
</tbody>
</table>
<?php $count++;
}
foreach($a as $b) {
$x = isset($x[$c]) ? $x[$c] : "foo7";
echo $x;
}
Let us "run" that piece of code, assuming
$x = array('c' => 'lat,lng');
before the loop.
So loop #1 prints 'lat,lng'.
Loop #2 checks if isset('lat,lng'[$c]), evaluates to false, so $x will be 'foo'.
'foo' will be printed.
Loop #3 does the same as #2, but checks if isset('foo'[$c]), again evaluating to false.
Again 'foo' will be printed.
That's the reason.
I don't know what else you are doing outside that loop and most of the code seems to do nothing or nothing intended really.

Allowing client to add data to an array which will display to a table when submit button is clicked

So here is the situation. I have a program that takes data from an array and displays it on a table. I created text input types that allows a client to input new items and when the submit button is clicked, all fields are added to the table. I was thinking if there was a way to write the arrays to the text file and do a fwrite to write the clients input to the text file. Also I notice that the text file keeps getting overwritten so the data inputted would not retain, instead of
$handle=fopen($myfile, "w");
should I use
$handle=fopen($myfile, "a");
Would amend work if no file exists and it will create the text if its not there?
When I run the code I partially borrowed and created, the clients new table is not added to the already existing table.
Sorry if this is unclear, I am a novice. Any help would greatly be appreciated and if you need more information please let me know.
Here is the code I have developed so far:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<center>
<?php
$myfile = "file1.txt";
if(!empty($_POST['product_name']))
{
$newData=nl2br(htmlspecialchars($_POST['ta']));
//////////////////////////////////////////////////
//the following variables are grabbing specific information from the form.
$product_name = array($_POST['product_name']);
$product_descriptoin = array($_POST['product_description']);
$price = array($_POST['price']);
$image = array($_POST['image']);
echo '<table border="1" align="center" cellpadding="10">';
echo "<tr align='center'>
<td><b>Product Name</b></td>
<td><b>Product Description</b></td>
<td><b>Price</b></td>
<td><b>Image</b></td>
</tr>";
foreach ($product_name as $key=>$newData) //this is suppose to add client input
//to a table.
{
echo "<tr align='center'>";
echo '<td>';
echo $product_name[$key];
echo '</td>';
echo '<td>';
echo $product_descriptoin[$key];
echo '</td>';
echo '<td>';
printf('$%', $price);
echo $price[$key];
echo '</td>';
echo '<td>';
echo "<img src='".$image[$key]."' width='200' height='300' align='center'>";
echo '</td>';
}
echo '<tr>';
echo '<td>';
echo '<td>';
echo '<td>';
echo '<td>';
echo '</td>';
echo '</td>';
echo '</td>';
echo '</td>';
echo '</tr>';
echo '</table>';
// /////////////////////////////////////////////
$handle=fopen($myfile, "w");
fwrite($handle, $newData);
fclose($handle);
}
?>
<?php
if (file_exists("$myfile"))
{
$myData= file_get_contents($myfile);
}
?>
<form action ="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000000000" />
<h1>Product Information Page</h1>
<p>Product Name: <input type="text" name="product_name" /></p>
<p>Upload Product Image: <input type="text" name="image" id="image"</p>
<p>Description: <input type="text" name="product_description" /></p>
<p>Price: <input type="text" name="price" /></p>
<br/><br/>
<input name="submit_btn" type="submit" />
</form>
<br/>
<br/>
<br/>
<?php echo $myData; ?>
<?php
//Orlando's mini assignment 3
//arrays that include pictures and all information
$product1 = array('Product Name'=> 'Beauty Boxer Shorts', 'Product Image'=>'<img src= 001.jpg height="88" width="110">', 'Description' => 'Beauty Boxer Shorts', 'Price (each)' => '$14.95');
$product2 = array('Product Name'=> 'Girl Generation Shorts', 'Product Image'=>'<img src= 002.jpg height="88" width="110">', 'Description' => 'Girl Generation Shorts', 'Price (each)' => '$15.95');
$product3 = array('Product Name'=> 'Pick Shorts', 'Product Image'=>'<img src= 003.jpg height="88" width="110">', 'Description' => 'Pick Shorts', 'Price (each)' => '$22.95');
$product4 = array('Product Name'=> 'Red Bull Shorts', 'Product Image'=>'<img src= 004.jpg height="88" width="110">', 'Description' => 'Red Bull Shorts', 'Price (each)' => '$24.95');
$product5 = array('Product Name'=> 'White with Gold <br> Dragon Shorts', 'Product Image'=>'<img src= 005.jpg height="88" width="110">', 'Description' => 'White with Gold <br> Dragon Shorts', 'Price (each)' => '$25.95');
// array of all products
$products = array($product1, $product2, $product3, $product4, $product5);
//setup an html table
echo "<table border=1>";
//prints the table header
echo "<tr>";
$header = array_keys($product1);
foreach ($header as $key => $head)
{
echo "<th>$head</th>";
}
echo "</tr>";
//iterate through the table body, printing each row
for($i=0; $i<count($products); $i++)
{
echo "<tr>";
foreach($products[$i] as $key => $value)
{
echo ("<td><center>$value</center></td>");
}
echo "</tr>";
}
?>
</body>
</html>
</center>
If you must use a text file instead of a database, then your best approach would be to append the table row data to the file in CSV format.
The first part of your script should handle the form input, preferably validating each field, but in the simplest form, you can create an array from the POSTed data. Then you can use fputcsv() to write to the file, and fgetcsv() to get the CSV data into an array so you can display it in the table.
<?php
/**
* Ensure you have the full path to the file on the file system
*/
$myFile = dirname(__FILE__).DIRECTORY_SEPARATOR.'file.txt';
/**
* This section handles the form submit
*/
// Create a boolean value checking the necessary data is posted
$check = isset(
$_POST['product_name'],
$_POST['product_description'],
$_POST['price'],
$_POST['image']
);
// Do we have the data?
if ($check) {
// Open the file to append a new row
$fh = fopen($myFile, "a");
// Create an array of data from the POSTed vars
$dataRow = array(
$_POST['product_name'],
$_POST['product_description'],
$_POST['price'],
$_POST['image']
);
// Write the data to file in CSV
fputcsv($fh, $dataRow);
// Close the file
fclose($fh);
}
/**
* Then we re-open the file for reading
*/
$fh = fopen($myFile, "r");
/**
* The next section displays the table
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<form action="/" method="post">
<p>
<label for="product_name">Product Name</label>
<input id="product_name" name="product_name" type="text"/>
</p>
<p>
<label for="product_description">Product Description</label>
<input id="product_description" name="product_description" type="text"/>
</p>
<p>
<label for="price">Price</label>
<input id="price" name="price" type="text"/>
</p>
<p>
<label for="image">Image</label>
<input id="image" name="image" type="text"/>
</p>
<input type="submit" value="Submit"/>
</form>
<table border="1" align="center" cellpadding="10">
<tbody>
<thead>
<tr>
<th>Product Name</th>
<th>Product Description</th>
<th>Price</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<?php
/**
* Here you can loop through each row in the file, getting an array of
* data from the CSV values
*/
$data = fgetcsv($fh);
?>
<?php while (($data = fgetcsv($fh)) !== false) : ?>
<tr>
<td><?php echo htmlentities($data[0]); ?></td>
<td><?php echo htmlentities($data[1]); ?></td>
<td><?php echo htmlentities($data[2]); ?></td>
<td><?php echo htmlentities($data[3]); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</tbody>
</table>
</body>
</html>
<?php
/**
* Finish off by closing the file
*/
fclose($fh);
?>

Storing data in mysql using two dimensional array

Here is the form that collects employer's history and stores that data into 2d array, then I am trying to store that info into mysql database in a table employment. It gives me no error but it can't store data into mysql ..
form1.php
<form action="result.php" method="post">
<table width="676" border="0" cellspacing="0" cellpadding="7" align="center">
<tr><td colspan="6" bgcolor="#C0C0C0">EMPLOYMENT HISTORY</td></tr>
<?php
for ($x=0; $x<2; $x++)
{
?>
<tr>
<td colspan="3" align="left">NAME OF EMPLOYER<br>
<input type="text" name="emp[emp_name][]" size="38"></td>
<td align="left">JOB TITLE <br>
<input type="text" name="emp[emp_title][]" size="32"></td>
</tr>
<tr>
<td colspan="5" valign="top">ADDRESS<br>
<input type="text" name="emp[emp_addr][]" size="58"></td>
</tr>
<tr>
<td colspan="2" valign="top">REASON FOR LEAVING<br>
<textarea name="emp[emp_reason][]" cols="25" rows="3"></textarea></td>
</tr>
<tr>
<td align="left">DATE STARTED<br>
<input type="text" name="emp[emp_start][]" size="8"></td>
<td align="left">DATE ENDED<br>
<input type="text" name="emp[emp_end][]" size="8"></td>
<td colspan="2" align="left">TYPE OF BUSINESS<br>
<input type="text" name="emp[emp_btype][]" size="15"></td>
</tr>
<tr><td colspan="6" bgcolor="#C0C0C0"> </td></tr>
<?php } ?>
</table>
<input type="submit" name="submit" value="SUBMIT"> <input type="reset" value="RESET">
</form>
here is the result.php
<?php
// open connection to the database
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('userdb');
// get all the values
$app_id = 5;
$app_emp = array($emp => array(
$emp_name => $_POST["emp_name"],
$emp_title => $_POST["emp_title"],
$emp_addr => $_POST["emp_addr"],
$emp_reason => $_POST["emp_reason"],
$emp_start => $_POST["emp_start"],
$emp_end => $_POST["emp_end"],
$emp_btype => $_POST["emp_btype"]
));
// set up error list array
$errorList = array();
$count = 0;
// validate
// making sure that they are filling in all the required fields for the employer for each of the 3 "boxes"
for ($x=0; $x<sizeof($app_emp); $x++)
{
if(!empty($emp_name[$x]) || !empty($emp_start[$x]) || !empty($emp_end[$x]))
{
if(empty($emp_start[$x]) || empty($emp_end[$x]))
{
$errorList[$count] = "Invalid entry: Employment History, item " . ($x+1);
$count++;
}
}
}
// if no errors
if (sizeof($errorList) == 0)
{
// insert employment history
for($i=0; $i<sizeof($emp_name); $i++)
{
$x = 0;
if (!empty($emp_name[$i][$x]) && !empty($emp_start[$i][$x]) && !empty($emp_end[$i][$x]))
{
$query = "INSERT INTO `employment` (`app_id`,`name`,`title`,`addr`,`reason`,`start`,`end`,`bustype`) VALUES ('$app_id', '$emp_name[$x]', '$emp_title[$x]', '$emp_addr[$x]','$emp_reason[$x]', '$emp_start[$x]', '$emp_end[$x]', '$emp_btype[$x]')" or die(mysql_error());
$result = mysql_query($query, $conn) or die ("Error in query: $query. " . mysql_error());
}
}
// If it gets processed, print success code
echo "Your information has been accepted.";
}
else
{
?>
<table width="676" border="0" cellspacing="0" cellpadding="8" align="center">
<tr><td>
<?php
// or list errors
listErrors();
?>
</span></td>
</tr>
</table>
<?
}
?>
<?php
// print out the array
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
I know you have found a solution. Just incase someone found this and get curious :)
There are couple of issues with the logic
For start under this line:
// get all the values
$emp will be empty '' all the time as it is not initialised and if you initialise the entire logic will shatter.
Also the $_POST you have mentioned will always be empty. You need to address it from them Master (Level1) Just var_dump($_POST) and you see what I mean :)
So do something like this: (I must stress this is not a good approach but just to shed some light on this question)
var_dump($_POST['emp']); // This is master array that holds everything
$app_emp = array();
foreach ($_POST['emp'] as $key => $val) {
$app_emp[0][$key] = mysql_real_escape_string($val[0]);
$app_emp[1][$key] = mysql_real_escape_string($val[1]);
}
// set up error list array
$errorList = array();
$count = 0;
var_dump($app_emp);
Now in the $app_emp you have got 2 separate arrays that you can go through, validate and add them to DB. Of-course the current SQL is not going to work as you need to wiggle it to fit the new array. Rest should be easy.
Couple Of handy note:
I am sure you are cleaning up your form submit mysql_real_escape for
all the vars.
Also try to use redirection after successful submit,
as users will intend to refresh the page. Otherwise user is going to
get ugly do you want to resubmit the data.
Make sure you pass a token to the result page, and check it there. I would use a random DB number so stop the Cross Browser hacks.
Hope this help. H.

Posting Multiple Input Text Value with Same (input)Name

I am using php to insert into Microsoft SQL table and the below is my code:
$server = "**/**,1433";
$connectionInfo = array( "Database"=>"***", "UID"=>"**", "PWD"=>"******" );
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$sql = "SELECT Item.HQID, Item.ItemLookupCode, Item.Description, Item.ExtendedDescription, Item.SalePrice, Item.Price, Item.CategoryID FROM Item WHERE Item.HQID = '$check'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$html_table = '<table border="1" cellspacing="0" cellpadding="2">';
$html_table .= '<form method="post" action="upload.php"><tr><td width="350" align ="center">' .$row['Description']. '</td><td width="350" align ="center">' .$row['ExtendedDescription']. '</td><td width="130" align="center">'
.$row['ItemLookupCode']. '<td width="100" align="center">' .$row['SalePrice']. '</td><td width="100" align="center">' .$row['Price']. '</td><td width="200" align="center"><input
type="text" size="24" name="stitle"></td><td width="100" align="center"><input type="text" size="8" name="wprice"></td><td width="120" align="center"><input type="text" size="10" name="scategory"></td><td width="220" align="center"><input
type="text" size="28" name="sbody"></td></tr>';
$html_table .= '</table>';
echo $html_table;
}
}
}
}
?>
<input type="submit" value="Upload this page" ></form>
I have an <input> with name="stitle" and I want the PHP code to take values from each <input> but currently it picks up the value just from the first <input>. How do I fix this?
Your post is horrible formatted, but I think you're looking for the array notation.
You can make something like that:
<input type="text" size="24" name="stitle[]">
The $_POST array field stitle is an array with all values after submitting the form.
OK, a simple example of the form, ignoring all extra syntactical mark-up
<pre>
<?php print_r($_POST); ?>
</pre>
<form method="POST" action="">
<input type="text" size="24" name="stitle[]" />
<input type="text" size="24" name="stitle[]" />
<input type="text" size="24" name="stitle[]" />
</form>
Now, anything you enter into those three text boxes will all be returned, and be accessible in the "$_POST" variable.
If you do not want to use the array style inputs [] and you have control over the qty of fields then you can also do the following:
for($f=0; $f < 5; $f++){
echo '<input type="text" name="foo_'.$f.'">';
}
/*-----------server-side------------*/
for($f=0; $f < 5; $f++){
if(isset($_POST['foo_'.$f])){
//do something
}
}
You can use this simple code for multiple simple input
$stitle=$_POST['stitle'];
for($j=0;$j<count($stitle);$j++)
{
echo $stitle[$j]."<br>";
}

Categories