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]}) ");
}
Related
I am trying to export a full table into SQL using data from an HTML table. I know how to export one row, but can't understand how to export multiple rows. Any advice?
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<form action="insertorder.php" method="post">
<td name="Item_ID[]"><?=$row["item_id"]?></td>
<td name="name[]"><?=$row["ITEM_NAME"]?></td>
<td name="suggested_qty"><?=$row["suggested_qty"]?></td>
<td name="price" class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result[]' class="resultinput" /></td>
</tr>
<?php endwhile?>
<input type="submit" class="btn btn-dark" value="Submit">
</table>
</form>
Export script:
$sql = "INSERT INTO ms_order VALUES (item_id, item_name, order_quantity, total)";
for ($i=0; $i<count($_POST['Item_ID']); $i++) {
$sql .= '(\'' . $_POST['Item_ID'][$i] . '\', \'' . $_POST['name'][$i] . '\', \'' . $_POST['editedvalues'][$i] . '\', \'' . $_POST['result'][$i] . '\')';
if ($i<count($_POST['Item_ID']) - 1) {
$sql .= ',';
}
echo $sql;
}
The problem on your code it's that you're creating a new form for each fetched row on the while loop. By doing this, you're sending only one row whenever the form is submitted. To solve this you should place the form tag outside the while loop. Also, let me share with you a cleaner way to accomplish what you're doing:
$sql = "INSERT INTO ms_order (item_id, item_name, order_quantity, total) VALUES ";
$sql .= implode(',', array_map(function($item_id, $name, $editedvalues, $result) {
return <<<SQL
({$item_id}, {$name}, {$editedvalues}, {$result})
SQL;
}, $_POST['Item_ID'], $_POST['name'], $_POST['editedvalues'], $_POST['result']));
This is what it does:
array_map function fetchs each index of a given array, you can pass as an argument as many arrays as you wish, it will iterate over each index so you will be able to use each value to manipulate it and return it.
Each iteration of the array_map will create a new array, so in the end what you get is an array of arrays containing the returned results. Finally, as you want to make a multiple INSERT, you concatenate each array with a colon using the implode function.
Note that you should sanitize the $_POST values as you might be vulnerable to SQL Injection and other security issues. For further information about it, check it out here.
Greetings,
Matt
I have a code which should delete a selected ID row from table by loading a remove.php file with SQL query. The problem is that it doesn't work but I get no errors or notices. My variable seems to get transfered to remove.php in URL just fine, as '<a href="remove.php?='.$Fvalue.'">' gets interpreted as
remove.php?=1
for example, where 1 is primary id of the row.
Here is all the code related to the question only:
EDIT:
Rendered HTML for products table with REMOVE button:
<!-- Products table -->
<table class="table">
<thead>
<tr>
<th scope='col'>id </br ></th><th scope='col'>name </br ></th><th scope='col'>price </br ></th><th scope='col'>amount </br ></th><th scope='col'>category_name </br ></th> </tr>
</thead>
<tbody>
<tr><td data-id="1"> REMOVE</td>
<td>iPhone 7</td>
<td>800</td>
<td>15</td>
<td>Smartphones</td>
</tr><tr>
<td data-id="42"> REMOVE</td>
<td>Motorola </td>
<td>3000</td>
<td>5</td>
<td>Smartphones</td>
</tr><tr><td data-id="2"> REMOVE</td><td>Macbook Pro 2015</td>
<td>1300</td><td>10</td>
<td>Computers</td></tr><tr><td data-id="4"> REMOVE</td>
<td>Dell XPS</td>
<td>1400</td>
<td>6</td><td>Computers</td>
</tr><tr><td data-id="41"> REMOVE</td>
<td>CHROMEBOOK</td>
<td>5600</td>
<td>8</td>
<td>Computers</td></tr></tbody>
Updated PHP:
<?php
foreach ($newArray as $value) {
echo '<tr>';
foreach ($value as $key => $Fvalue) {
$remove = $value['id'] = " REMOVE";
if($value[$key] == $value['id']) {
echo '<td data-id="'.$Fvalue.'">' . '' . $remove . '' . '</td>'; // will show all values.
} else {
echo '<td>' . $Fvalue . '</td>';
}
}
echo '</tr>';
}
?>
remove.php
<?php
require_once ("navigation.php");
require_once("database_connection.php");
$id = !empty($_GET['remove_id']) ? $_GET['remove_id'] : null;
if($id != null) {
$deleteProducts = "DELETE FROM `products` WHERE `id` = '.$id.'";
mysqli_query($dbc, $deleteProducts);
}
Looking for any help to me spot any problems as I get no errors and have no idea why the code is not deleting a row in the table. Thanks.
You have to pass a key associated with the value you are sending;
' . $remove . '
Notice the remove_id part.
Now, in your PHP you can retreive this value;
$id = !empty($_GET['remove_id']) ? $_GET['remove_id'] : null;
if($id !== null) {
$deleteProducts = "DELETE FROM `products` WHERE `id`='{$id}'";
mysqli_query($dbc, $deleteProducts);
}
In my code here, I also fixed an issue you had in your code. You had $id = (isset($_GET['$Fvalue']));, which will always set $id to true or false, not to the ID that you had passed.
You can also clean up your HTML variables by using a double quote instead of a single quote.
if($value[$key] == $value['id']) {
echo "<td data-id='{$Fvalue}'><a href='remove.php?remove_id={$Fvalue}'>{$remove}</a></td>"; // will show all values.
} else {
echo "<td>{$Fvalue}</td>";
}
BIG NOTE:
Little Bobby says you may be at risk for SQL Injection Attacks. Learn about Prepared Statements with parameterized queries.
Using the get method, you need key-value pairs in your url.
remove.php?id=1
Where id is the key and 1 is the value.
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
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.
here's my problem:
I have a form in which user inputs 3 things (ID key, Date from and Date To) and also from a group o checkboxes he chooses which columns he wants to see in the result. (the form is way to big because its database table has about 15 columns each, so I don't post it here)
here is the (part of the) code which handles these inputs and generates the query. (I'll explain after it what exactly does)
<?php
//Check the columns that should be shown in the table
if(empty($_POST['vesselcolumns']) && empty($_POST['expeditioncolumns'])){
$columns='*';
}else if (isset($_POST['vesselcolumns']) || isset($_POST['expeditioncolumns'])) {
if (empty($_POST['vesselcolumns'])){
$columns='';
}else{
$vesselcolumns= implode(',', $_POST['vesselcolumns']);
$columns=$vesselcolumns;
}
if (empty($_POST['expeditioncolumns'])){
$columns.='';
}else{
$expeditioncolumns = implode(',', $_POST['expeditioncolumns']);
if($columns!=''){
$columns.=','.$expeditioncolumns;
}
}
}
//AMAS check
if(empty($_POST['searchv'])){
echo 'No AMAS given, will print ALL expedition data<br />';
}else{
$amas = $_POST['searchv'];
}
//Deploy Date FROM and TO check
if(empty($_POST['deploydatefrom'])){
$datefrom = '0000-00-00';
}else{
$datefrom = $_POST['deploydatefrom'];
}
if(empty($_POST['deploydateto'])){
$dateto = '9999-12-31';
}else{
$dateto = $_POST['deploydateto'];
}
if(isset($amas)){
$expeditionq="SELECT '$columns'
FROM vessel
INNER JOIN vessel_expeditions
ON vessel.AMAS=vessel_expeditions.vexpedition_AMAS AND vessel.AMAS= '$amas'
INNER JOIN expedition
ON vessel_expeditions.expedition_ID=expedition.expedition_ID
WHERE expedition.deployDate >= '$datefrom' AND expedition.deployDate <= '$dateto'";
$result=mysqli_query($con,$expeditionq);
if($columns=='*'){
$takefields=mysqli_query($con, "SHOW COLUMNS FROM vessel");
while ($vcol = mysqli_fetch_array($takefields)){
$vcolu= array( $vcol['Field']);
}
$takefieldse=mysqli_query($con, "SHOW COLUMNS FROM expedition");
while ($ecol = mysqli_fetch_array($takefieldse)){
$ecolu= array($ecol['Field']);
}
$vccounter = count($vcolu);
$eccounter = count($ecolu);
while($row = mysqli_fetch_array($result)){
for($i=0; $i<$vccounter; $i++){
echo $row[$vcolu[$i]] . '<br />';
}
for($i=0; $i<$eccounter; $i++){
echo $row[$ecolu[$i]] . '<br />';
}
}
}else{
$column = explode(',', $columns);
$counter = count($column);
$forexport='<table id="results">
<tr>';
for($i=0; $i<$counter; $i++){
$forexport .= '<th>' . $column[$i] . '</th>';
}
$forexport.='</tr>';
while($row = mysqli_fetch_array($result)){
for($i=0; $i<=$counter; $i++){
$forexport .= '<td>' . $row[$column[$i]] . '</td>';
}
$forexport.='</tr>';
}
$forexport .='</table>';
echo $forexport;
echo '<form name="exportanalysis" method="post" action="exportanalysis.php">
<input type="hidden" name="export" value="' . htmlspecialchars($forexport, ENT_QUOTES) . '" />
<label for="selectcsv"><img src="img/csv-icon.png" width="50" height="50" /> </label>
<input type="radio" name="filexport" value="csv" id="selectcsv" required />
<label for="selectxls"><img src="img/xls-icon.png" width="50" height="50" /> </label>
<input type="radio" name="filexport" value="xls" id="selectxls" />
<input type="submit" value="Download" />';
}
}else{
echo 'amas not set';
}
?>
First I check which columns has user selected (if none selected I put "*") and I break them in an array with implode (as from the checkboxes they come in string like this: column1,column2,column4, etc.).
Then I check the AMAS (which is the ID key user inputs) and finally I check the dates if given [strange thing here when I submitted the form without date values with isset() even though there was no value in them it kept passing the if(as they were set) so I changed it to empty()].
After multiple tests I've found out that the query ($expeditionq) works fine (I even tested it in MySQL directly). Also the "SHOW COLUMNS" queries work fine and I fetch their results and showed them.
The problem comes when I'm trying to show the results of the $expeditionq query and I assume that the problem is this: $row[$column[$i]] but I cannot figure out another way to do it :/
Puh. Sorry this code looks weired. Is this what you want to express:
if(!empty($_POST['vesselcolumns']) && !empty($_POST['expeditioncolumns'])){
$columns= implode(',', $_POST['vesselcolumns']) . ',' . implode(',', $_POST['expeditioncolumns']);
}
else if(!empty($_POST['vesselcolumns'])) {
$columns= implode(',', $_POST['vesselcolumns']);
}
else if(!empty($_POST['expeditioncolumns'])) {
$columns= implode(',', $_POST['expeditioncolumns'])
}
else {
$columns='*';
}
Anyway, the problem is just obvious:
SHOW COLUMNS will return all columns in that table.
You iterating over the result, which contains only the columns the user selected.
So you are trying to access alphanumeric indexes or "keys" within the row that dont exist unless the user has requested to show all columns.
EDIT: Sorry, this was an incomplete reading due to the unstructured way the source is organized. The query SHOW COLUMNS is only executed, when $columns == "*", so all fields are selected obviously.