php submit only giving last value from array that populates form - php

Struggling with a one page form that i want to first populate a form from a mysql query, then enable a user to update some of the values in each of several table rows from text input fields in the form.
The code's intent is to update the field by referencing the row ID.
But for some reason I'm only able to update the last row in the form (the last row from the array). I've included some troubleshooting code to see what the ID variable is and it always comes up as the last iteration of the array. I think I'm either overwriting the ID variable in the while loop or the for loop.
I have tried moving the POST/update to a 2nd file but get the same results. Any thoughts/suggestions would be greatly appreciated
Here is the code minus the db connection:
$saveClicked = $_POST["saveClicked"];
{ // SAVE button was clicked
if (isset($saveClicked)) {
unset($saveClicked);
$ID = $_POST["ID"];
$win = $_POST["Winner"];
$winScr = $_POST["WinnerScore"];
$losScr = $_POST["LoserScore"];
$tschedule_SQLupdate = "UPDATE tschedule SET ";
$tschedule_SQLupdate .= "Winner = '".$win."', ";
$tschedule_SQLupdate .= "WinnerScore = '".$winScr."', ";
$tschedule_SQLupdate .= "LoserScore = '".$losScr."' ";
$tschedule_SQLupdate .= "WHERE ID = '".$ID."' ";
if (mysql_query($tschedule_SQLupdate)) {
echo '<p> the number of mysql affected rows is '.mysql_affected_rows().'</p>';
echo 'this is the value for post id '.$ID;
} else {
echo '<span style="color:red; ">FAILED to update the game.</span><br /><br />';
echo mysql_error();
}
}
// END: SAVE button was clicked ie. if (isset($saveClicked))
}
{ // Get the details of all associated schedule records
// and store in array: gameArray with key >$indx
$indx = 0;
$tschedule_SQLselect = "SELECT * ";
$tschedule_SQLselect .= "FROM ";
$tschedule_SQLselect .= "tschedule ";
$tschedule_SQLselect .= "WHERE week = 1 ";
$tschedule_SQLselect_Query = mysql_query($tschedule_SQLselect);
while ($row = mysql_fetch_array($tschedule_SQLselect_Query, MYSQL_ASSOC)) {
$gameArray[$indx]['ID'] = $row['ID'];
$gameArray[$indx]['Date'] = $row['Date'];
$gameArray[$indx]['week'] = $row['week'];
$gameArray[$indx]['Favorite'] = $row['Favorite'];
$gameArray[$indx]['Line'] = $row['Line'];
$gameArray[$indx]['Underdog'] = $row['Underdog'];
$gameArray[$indx]['OU'] = $row['OU'];
$gameArray[$indx]['Winner'] = $row['Winner'];
$gameArray[$indx]['WinnerScore'] = $row['WinnerScore'];
$gameArray[$indx]['LoserScore'] = $row['LoserScore'];
$indx++;
}
$numGames = sizeof($gameArray);
mysql_free_result($tschedule_SQLselect_Query);
}
{ // Output
echo '<form name ="postGame" action="'.$thisScriptName.'" method="post">';
echo '<table border="1">';
echo '<tr>
<th>ID</th>
<th class="date">Date</th>
<th class="num">Week</th>
<th>Favorite</th>
<th class="num">Line</th>
<th>Underdog</th>
<th class="num">OU</th>
<th>Winner</th>
<th>WScore</th>
<th>LScore</th>
<th>Save</th>
</tr> ';
for ($indx = 0; $indx < $numGames; $indx++) {
$thisID = $gameArray[$indx]['ID'];
$saveLink = '<input type = "submit" value = "Save" />';
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_ID;
echo $fld_saveClicked;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size =5 name="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td>'.$saveLink.'</td>
</tr> ';
}
echo '</table>';
echo '</form>';
echo' View Schedule';
}

You're using the same names for each field in each row, so when you post the form, only the last is accessible. Use array notation for the fields like this:
<input type="text" size =5 name="Winner[]">
^^
This will give you an array for $_POST['Winner'] instead of a single value. Do the same for the other <input> elements.
Also, the code that processes the form after it's submitted only processes one value. You'll need to modify that to loop through these arrays.
Warnings:
don't use mysql_*() for new code - it's depracated. Switch to mysqli_*() or PDO now.
Your code is susceptible to SQL injection. Escape your input variables with mysql_real_escape_string() (or the mysqli equivalent) or better, switch to prepared statements.

After some more research I think I understand the two answers already shared much better. However I have chosen a different path and have resolved my issue -I wrapped the form tags directly around each row:
echo '<form name ="postGame'.$indx.'" action="'.$thisScriptName.'" method="POST">';
$fld_saveClicked = '<input type="hidden" name="saveClicked" value="1"/>';
echo $fld_saveClicked;
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
echo $fld_ID;
echo '<tr>
<td>'.$gameArray[$indx]['ID'].'</td>
<td>'.$gameArray[$indx]['Date'].'</td>
<td>'.$gameArray[$indx]['week'].'</td>
<td>'.$gameArray[$indx]['Favorite'].'</td>
<td>'.$gameArray[$indx]['Line'].'</td>
<td>'.$gameArray[$indx]['Underdog'].'</td>
<td>'.$gameArray[$indx]['OU'].'</td>
<td><input type="text" size=5 name="Winner" id="Winner">'.$gameArray[$indx]['Winner'].'</td>
<td><input type="number" size=5 name="WinnerScore" id="WinnerScore">'.$gameArray[$indx]['WinnerScore'].'</td>
<td><input type="number" size=5 name="LoserScore" id="LoserScore">'.$gameArray[$indx]['LoserScore'].'</td>
<td><button type="submit" />Save</button></td>
</tr></form>';
}
One of the key trouble shooting steps was to use var_dump to validate that the $_POST actually contained data. I understand there are several ways this could be done including the responses shared by Hobo and Syed, as well as using javascript, but was really glad I could accomplish my goal with just php.

Your For Loop is storing the last value of the array in your form.
$fld_ID = '<input type="text" name="ID" value="'.$thisID.'"/>';
Store the ID value as an array in HTML form and when a form is posted get all the ID values and update using your same mysql update query.
Your winner and loser score are also returning the last array values.

Related

How to get user input to insert multiple records into database from table created with a for loop?

I have created a form that requires the user to input information on all fields and then submit the form. My goal is to get the user input and insert it into new records on the database. My current challenges are that since I used a for loop in PHP to create the table/form:
I can not access the input from $_POST
Not sure how to go about differentiating all of the rows and their inputs from each other (since I used a loop to create them). I was thinking an array...
Please see a screenshot of the form I am working with.
Below is what I have for my submit button.
if (isset($_POST['submit'])) {
$date = date('m\/d\/Y');
$ordnum = $_POST['cpOrderNumber'];
$ponum = $_POST['cpPoNumber'] . $_POST['cpPoNumberF'];
$palnum = $_POST['palnum'];
$casecount = $_POST['casecount'];
$cpsflot = $_POST['cpsflot'];
$sscc = $_POST['sscc'];
if(!empty($_POST['cpOrderNumber']) || !empty($_POST['cpPoNumber'])) {
require_once('mydatabase.php');
$query = "INSERT INTO ASN (date, ordnum, ponum, palnum, casecount, cpsflot, sscc )
VALUES ('$date', '$ordnum', '$ponum', '$palnum', '$casecount', '$cpsflot', '$sscc')";
$insert = sqlsrv_query($dbc, $query);
if( $insert === false ) {
die('Could not connect to database');
}
}
else {
die('Please enter the appropriate information');
}
sqlsrv_close($dbc);
}
And here is where I am having difficulty. I can get $date, $ordnum, and $ponum to insert into the database however $palnum will not. As you can see from what I've commented out I have tried to use an array.
<?php
for ($x = 1; $x < 25; $x++) {
echo
'<tr id="' .$x. '">
<td style="font-size: 160%" name="palnum" id="pallet">' .$x. '</td>
<td id="caseCount"><input type="number" name="casecount" id="inputText_Small" maxlength="2"/></td>
<td id="hilltopLot"><input type="text" name="cpsflot" id="inputText_Order" value="" maxlength="10"/></td>
<td id="sscc"><input type="number" name="sscc" id="inputText_Medd" value="" maxlength="4"/></td>
</tr>';
$palnum[$x] = $x;
//$palnum[$x] = 'palnum'.$x;
//$palnum = $palnumx.$x;
//$palnum1 = $palnum[1];
}
//echo count($palnumx);
//echo $palnum[1];
?>
i think you are looking for this. not 100% though. Basically, you can name an input wityh brackets to make it behave like an array in the post.
<input name="recurringName[]" value="moo" />
<input name="recurringName[]" value="moo2" />
if you do that, in the post you can access data this way
$_POST['recurringName'][0] == 'moo'
$_POST['recurringName'][1] == 'moo2'
i hope this helps! let me know if i did not understand you clearly

Turn PHP MySQL query output into variable

I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.
The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.
This part of the code works just fine.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.
<form method="post" action="?p=venda">
<input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
<input type="text" name="preco" value="<?php echo $row["preco"]; ?>">
<input type="submit" name="change" value="Efetuar">
</form>
I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).
Thanks in advance.
Assign $row to a variable and treat it as an array() outside the while loop.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$array = $row; // assign $row a variable.
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
// example
echo($array['nome']);
OK I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.
In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.
anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.
your display, I don't use spans, but I'll show you how I do it with tables.
So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:
<?php
//load it in a variable and trim the outside spaces away if you are entering this from a blank form
$id=trim($_POST[id]);
///this should look familiar to you
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
///but I use the shorthand method here to get my results.
$result = $conn->query($sql);
///Now we loop and shift colum information into variables
/// in a incremental loop, the colums are numbered starting with 0
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000">'.$nome.'</td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'</td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'</td>';
}
}
//////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
echo "</tr>";
}
echo "</table>";
You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:
$id=trim($_POST[id]);
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$nome=stripslashes($row['nome']);
$preco=stripslashes($row['preco']);
$status=stripslashes($row['status']);
echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;
///notice my quote usage above
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php
<?php
$sql = "SELECT nome, preco, status FROM produtos";
$result = $conn->query($sql);
echo "<table align=center bgcolor=e3fab5 ><td>";
echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
}
}
echo "</form></tr>";
}
echo "</table>";
echo "</div></table>";
?>

How to combine PHP array from user input with MySQL table for calculation (conceptually)?

I have a website, where a user can enter a time series (date; series) into a text area. The data is sent to the server using the POST method.
I have a few tables with different time series already stored in the MySQL database.
The user specified time series and those stored in the database should be combined for statistical calculations.
I store the user input into an array using explode and want to select the time series from the database using the date as the selector (WHERE date = $datefromuserinput).
I have two problems here:
The date format for the array does not match the one in MySQL (ISO, o-m-d) after several transformations (e.g. strtotime).
Also, the time series data type in MySQL is in DECIMAL (15,4) format, but the one in PHP is string (transformed to float).
Before trying to find solutions, I would like to know if my concept is right and best. Putting the user input into a MySQL table would make calculations faster (as I understand). However, several users can use the form simultaneously that would result in overwriting the entries in the new table in MySQL, right? Should I load the complete MySQL table into a PHP array (session necessary)?
I have read many solutions but could not find these answer. Any hint would be highly appreciated.
<?php
date_default_timezone_set('UTC');
//session_start();
//$datum = [];
if ($_POST['usersubmit']) {
if ($_POST['userinput1'] !=""){
if ($_POST['separator'] != ""){
if ($_POST['separator'] == comma){
$separatorsign = ",";
}
elseif ($_POST['separator'] == semicolon){
$separatorsign = ";";
}
else {
$separatorsign = "\t";
}
}
$userinput1 = $_POST['userinput1'];
$zeilen= explode("\n", $userinput1);
$daten = array();
foreach($zeilen as $zeile) {
list($datum, $zeitreihe) = explode($separatorsign, $zeile,2);
$datumkonv = strtotime($datum);
$daten[]['datum'] = date('o-m-d',$datumkonv);
$daten[]['zeitreihe'] = $zeitreihe;
}
$con = mysql_connect('localhost','username','pw');
if (!$con)
{
die('Could not connect: ' . mysql_error($con));
}
mysql_select_db("dbname");
$sql = "SELECT series FROM mytimeseries1 WHERE date = $daten[0]['datum']"; //[0] just for trying working with the first row
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
echo "$row->series";//["series"].'<br>';
$row = floatval($row);
$ergebnis = $row + 22;
echo $ergebnis; // $row is 100.5000 but $ergebnis returns 100.5023 ??
mysql_free_result($result);
mysql_close($con);
echo "<pre>";
//print_r ($result);
print_r ($row);
var_dump($row);
var_dump($ergebnis);
}
}
?>
<table width="800">
<tr>
<td width="400">
<form action="test.php" method="post">
<p><textarea style="overflow-y:scroll;resize:none;" name="userinput1" id="userinput1" cols="28" rows="12"></textarea></p>
<p>Separator<br>
<input type="radio" name="separator" value="comma">Comma</p>
<p><input type="radio" name="separator" value="tab">Tab</p>
<p><input type="radio" name="separator" value="semicolon">Semicolon</p>
</td>
<td width="400">
<p>Date Format<br>
<input type="radio" name="dateformat" value="yyyy-mm-dd">YYYY-MM-DD</p>
<p><input type="radio" name="dateformat" value="yyyy-dd-mm">YYYY-DD-MM</p>
<p><input type="radio" name="dateformat" value="dd-mm-yyyy">DD-MM-YYYY</p>
<p><input type="radio" name="dateformat" value="mm-dd-yyyy">MM-DD-YYYY</p>
<p><input type="radio" name="dateformat" value="ddmmyyyy">DD.MM.YYYY</p>
<p><input type="submit" name="usersubmit" value="GO"></p>
</form>
</td>
</tr>
</table>
<?php
EDIT: After trying for hours I think that it makes more sense to upload the user input array into a temporary table in MySQL (date format is accepted etc). I had to change the foreach()-part in the code above to:
for($y = 0;$y < count($zeilen);$y++){
list($datum, $zeitreihe) = explode($separatorsign, $zeilen[$y], 2);
$daten[$y]['datum'] = $datum;
$daten[$y]['zeitreihe'] = $zeitreihe;
}

Update mysql database fields with array php

I'm trying to achieve a multiple update in one submit. I have a table with a number of rows and want to be able to update one field in each row just by tabbing to the next insert box.
My code is thus:-
//start a table
echo '
';
//start header of table
echo '<tr>
<td width="60" align="center"><strong>Lab Item ID</strong></td>
<td width="60" align="center"><strong>Test Suite Name</strong></td>
<td width="60" align="center"><strong>Test Name</strong></td>
<td width="50" align="center"><strong>Result</strong></td>
</tr>';
//loop through all results
while ($row=mysql_fetch_object($sql)) {
//print out table contents and add id into an array and email into an array
echo '<tr>
<td align="center"><input name="id[]" value='.$row->lab_item_id.' readonly> </td>
<td align="center">'.$row->test_suite_name.'</td>
<td align="center">'.$row->test_name.'</td>
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
</tr>';
}
//submit the form
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';
//if form has been pressed proccess it
if($_POST["Submit"])
{
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
foreach( $_POST['id'] as $id ) {
$tresult = trim($_POST['test_result']);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
var_dump($tresult);
//redirect user
$_SESSION['success'] = 'Updated';
//header("location:index.php");
}
?>
When I print the $_POST arrays, everything is populating fine, however the variable is Null. I know I can't do a foreach on multiple arrays (at least I don't think I can) so is there some other trick I'm missing please? I can't be far away as the $_Post print has the right data in it.
Incidentally, the whole thing is generated by a query, so I never know how many records I'll have to update.
I've been looking at this (and other) forums, but can't seem to get a solution. I thought I understood arrays, but now I'm beginning to wonder!
edit - it's the $tresult variable that isn't working.
Many thanks,
Jason
Edit Thursday 21st Feb (05:41 UK time)
Thanks for your input everybody. I've solved this one now, and your collective advice helped. The code that finally cracked it is:-
//get data from form
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach ($id1 as $key => $value){
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id=$value ";
//execute query
Working through which variables etc were populated and what they were populated with was the key. Back to first principles, isn't it?
Cheers all.
J
Actually, you might get it done by doing a simpler (basic) form of for loop:
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
$numberOfData = count($_POST['id']);
for($index = 0; $index < $numberOfData; $index++)
{
$id = $_POST['id'][$index];
$tresult = trim($_POST['test_result'][$index]);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
I hope this helps.
Cheers
change the query like this :
$query = "UPDATE tbl_lab_item SET test_result=$tresult WHERE lab_item_id = $id";
By adding single quotes ' ' you tell it to read is as a String and not to take the value of the var.
Edit
Replace your foreach loop with the following and let me know :
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach( $id1 as $key => $value ) {
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id = '$key' ";
}
Problem is that you're telling PHP to build your input fields as arrays, but then treat it as a string later:
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
^^--- array
$tresult = trim($_POST['test_result']);
^^^^^^^^^^^^^^^^^^^^^--- no array key, so you're assigning the entire array
$query = "UPDATE tbl_lab_item SET test_result='$tresult'
^^^^^^^^^^--- array in string context
trim() expects a string, but you pass in an array, so you get back a PHP NULL and a warning. That null then gets stuffed into your SQL statement, and there's your problem.

Retrieve Loop textbox

page_form.php
echo '<div style="text-align:center;margin-left:25px;">
<form action="grad.php" method="post">
<table width-"100%">
<tr><th style="padding:12px;">LETTER </th>
<th style="padding:12px;">INTERVAL</th>
<th style="padding:12px;">GT</th>
</tr>';
for($i=0;$i<=5;$i++)
{
echo '<tr><td style="padding:12px;"><input type="text" name="letter_'.$i.'"></td>
<td style="padding:12px;"><input type="text" name="interval'.$i.'"></td>
<td style="padding:12px;"><input type="text" name="gt'.$i.'"></td>
</tr>';
}
echo '<tr><td><input type="submit" name="submit" value="submit"></td></tr>';
echo '</table>
</form>
</div>';
grad.php
$letter = $_POST['letter'];
$interval = $_POST['interval'];
$gt = $_POST['gt'];
$s = mysql_query("INSERT INTO grad_table(letter,markint,gradepoint) VALUES('$letter',$interval,$gt) ");
I have given all the textboxes in a forloop. when I click on submit I need to get all the 5 textbox values, but right now iam getting only the 1st row.
Database Structure
Field Type Collation Attributes Extra
id bigint(10) UNSIGNED AUTO_INCREMENT
letter varchar(255) utf+general_ci
markint bigint(10)
gt bigint(10)
Your textbox names are not letter, as you're using them - they are letter_0, letter_1, etc.
Also, interval is a MySQL reserved-word and you'll need to escape it using backticks: `interval`.
To retrieve all of them, you can hardcode all of their names such as $letter1 = $_POST['letter_1'];, or you can do it in another loop:
for ($i=0; $i<5; $i++) {
$letter = $_POST['letter_' . $i];
$interval = $_POST['interval' . $i];
$gt = $_POST['gt' . $i];
$s = mysql_query("INSERT INTO `grad_table` (`letter`, `interval`, `gt`) VALUES ('$letter',$interval,$gt)");
}
One big thing to note here is that you should really validate your user-input before inserting it into the database. First, you can use isset() before accessing the variables to make sure the user submitted the data. Second, you can use mysql_real_escape_string() to sanitize the string input and intval() for the integers:
for ($i=0; $i<5; $i++) {
// check that each field is posted
if (!isset($_POST['letter_' . $i]) || !isset($_POST['interval' . $i]) || !isset($_POST['gt' . $i])) continue;
// assign & sanitize
$letter = mysql_real_escape_string($_POST['letter_' . $i]);
$interval = intval($_POST['interval' . $i]);
$gt = intval($_POST['gt' . $i]);
$s = mysql_query("INSERT INTO `grad_table` (`letter`, `interval`, `gt`) VALUES ('$letter',$interval,$gt) ");
}
Now, this doesn't "validate" your data, but at least it will help prevent SQL injection and simply PHP errors.
Your post data should containt $_POST['interval0'], $_POST['interval1'], $_POST['interval2']...
You will have to trawl through each $_POST to get all the answers. I an frankly surprised you are getting any post data with your code as it is.
you should modify following
for($i=0;$i<=5;$i++)
{
echo '<tr><td style="padding:12px;"><input type="text" name="letter['.$i.']"></td>
<td style="padding:12px;"><input type="text" name="interval['.$i.']"></td>
<td style="padding:12px;"><input type="text" name="gt['.$i.']"></td>
</tr>';
}
then you can do following
foreach($_POST['letter'] as $i=>$v) {
mysql_query("INSERT INTO grad_table(letter,interval,gt) VALUES('{$_POST['letter'][$i]}',{$_POST['interval'][$i]},{$_POST['gt'][$i]}) ");
}

Categories