How can I keep a value in a dropdown list - php

I have a form with many entries, there are many selects that get their data from a table in mysql, that works fine, my form sends all the inputs to $_post just fine. The problem is with the select portion. The page loads info from a mysql table and populates all the fields with the exception of the select field. The select field shows to the user a text name and passes a 2 digit number to the Post. The problem is that when the page loads the Post for all the select fields is populated with the value of the first select object in the list. So, in a nutshell all the (40) fields get overwritten when I submit. Unless I go through all the dropdowns and set them back to the original settings they all change, not ideal.
echo "<tr><form action='update.php' method='post'>";
echo"<td><input type='hidden' name='id' value='".$row['id']."'></td>";
echo"<td><input type='hidden' name='name' value='".$row['templatename']."'></td>";
echo"<td><input type='text' name='keyname1' value='".$row['keyname1']."'><readonly</td>";
echo"<td></select><select name='lk1'>";
while($rowA = mysqli_fetch_assoc($result1)) {
echo '<option value="' . $rowA['keytype'] . '">' . $rowA['keyname'] . '</option>';
}
echo"</select></td>";
echo"<td><input type='text' name='lk1value' value='".$row['lk1value']."'></td>";
echo"<td><input type='text' name='lk1label' value='".$row['lk1label']."'></td>";
echo "<td><input type='submit'>";
Thanks

You can mark an <option> element in a <select> list as the start/default value by using the selected="selected" attribute. When you are in the while loop and have checked that the current $row entry is the one the user has selected before, you can generate the output as follow:
while ($rowA = mysqli_fetch_assoc($result1)) {
if ($row['yourFieldInTheDatabase'] == $rowA['keytype']) {
echo '<option value="'.$rowA['keytype'].'" selected="selected">'.$rowA['keyname'].'</option>';
} else {
echo '<option value="'.$rowA['keytype'].'">'.$rowA['keyname'].'</option>';
}
}

Related

Differentiate between multiple buttons on a table. html php

I am creating an edit edit/delete user table and have created an 'edit' button for each record populated in the table. I want to do several things.
1. when an edit button is pressed for a specific user, open a new page called "EDIT."
2. populate form controls in the "EDIT" page with the corresponding user information for the specific 'edit' button that was pressed.
My question is, how do I differentiate between which button is pressed on the users table?
this is what my table looks like:
And this is the code for generating the table and buttons.
if (!$_REQUEST['search']) {
$sql = "SELECT * FROM users_table ORDER BY lname ASC";
$retvalues = mysqli_query($conn, $sql);
$counter = 1;
while ($row = mysqli_fetch_array($retvalues, MYSQL_ASSOC)) {
$lname = capword($row['lname']);
$fname = capword($row['fname']);
if ($row['admin'] != 1) {
$stringAdmin = "No";
$admincolor = "<td>";
} else {
$stringAdmin = "Yes";
$admincolor = "<td style='color:red;'>";
}
echo "<tr>";
echo "<td>".$counter.".</td>";
echo "<td>".$lname." , ".$fname."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['password']."</td>";
echo $admincolor.$stringAdmin."</td>";
echo "<td><input type='checkbox' name='user[]' value='{$row['id']}'></td>";
echo "<td><input type='submit' name='edit' value='edit'></td>";
echo "</tr>";
$counter++;
}
}
You can differentiate the each edit button by using unique id
<button class='edit' data-id="<?php echo $_GET["id"];?>"> EDIT</button>.
While click on the edit button, read the data-id by using the following code
$(document).on('click', '.edit', function(){
var id = $(this).attr('data-id');
//code - you need to do
})
Better to show the data on next page, use bootstrap model box and AJAX request which will interact lot of the users.
$(document).on('click', '.edit', function(){
var id = $(this).attr('data-id');
if(id) {
$.ajax({
url : your url("profile/edit/"+id)
type : 'post',
success: function(response){
if (response.success) {
$('#modal').modal('show');
}
}
}):
}
});
If you change the value attribute of "Edit" submit button to the row id you can use this value to know what record id will be edited and populate it.
"<input type='submit' name='edit' value='edit'>"
change to
"<button name='edit' value='{$row['id']}'>Edit</button>"
Note that if the whole table is the form container, all inputs in table will be posted, not only the current row.
I would make the edit button into a hyperlink instead. Then there's no need to have form code. I'm assuming you don't need to pass the "delete" parameter to your edit page (as that's a different operation).
Instead of
echo "<td><input type='submit' name='edit' value='edit'></td>";
write
echo "<td><a href='edit.php?id=".$row['id']."'>Edit</a></td>";
Then in edit.php look for the variable
$_GET["id"]
and use that to search the database and display the appropriate record for editing.
P.S. If you still want your "Edit" hyperlink to look like a button it's quite easy to do that with CSS.
I did this by creating and calling a javaScript function that passes the id of the row as an argument.
echo"<tr>";
echo"<td>".$counter. ".</td>";
echo"<td>".$lname. " , " .$fname."</td>";
echo"<td>".$row['email']."</td>";
echo"<td>".$row['password']."</td>";
echo $admincolor . $stringAdmin ."</td>";
echo"<td><input type='checkbox' name='user[]' value='{$row['id']}'></td>";
echo"<td><input type='button' name='edit' value='edit' onclick='javascript:editUser(". $row['id'].");'></td>";
echo"</tr>";
the function redirects the user to an 'edit' page while passing the value of the id in the url.
function editUser(id){
window.location = "edituser.php?id="+id;
}
once on the edit page, i used $_GET to retrieve the id value and edit my entry.
You can change and add a form to your table like this:
echo "<tr>";
echo "<td>".$counter.".</td>";
echo "<td>".$lname." , ".$fname."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['password']."</td>";
echo $admincolor.$stringAdmin."</td>";
<form action="edit.php" method="post">
echo "<input type="text" name="id" value="$row['id']" style="visibilty: hidden;">";
echo "<td><input type="checkbox" name="delete"></td>";
echo "<td><input type="submit" name="edit" value="edit"></td>";
</form>
echo "</tr>"
First we have defined a form with POST method: <form action="edit.php" method="post"> and let's say edit.php will handle the request.
Then we have added a hidden form element to store and pass the user's ID: <input type="text" name="id" value="$row['id']" style="visibilty: hidden;"> It was possible to use value="..." of "edit" button but if you are dealing with passing more than one variables with POST or GET method, the trick is using an extra form element with visibility: hidden; CSS property.
Eventually, it will pass the value of $row['id'] to edit.php when the form has been submitted.
and we can handle the request in edit.php like this:
<html>
<body>
User with this ID number: <?php echo $_POST["id"]; ?> will be edited.
</body>
</html>
Official guide: http://php.net/manual/en/tutorial.forms.php
You can either use POST or GET method to pass the variables. For a detailed comparison: https://stackoverflow.com/a/504993/2104879

Ajax Function when search results page has same field ID names

I am working on a script that prints an HTML table from an SQL table, based on results of a search. The table will print a button if the value of a particular field is not 1. So, in different search results, there could be various buttons printed on the table. When you press the button, the value of that field should update to 1 via AJAX call.
Here's the PHP code for printing the table:
echo "<title>Search Results</title>";
if (!$query->rowCount() == 0) {
echo '<table style=\"width:100%\"><tr>
<th class="text-left">Name</th>
<th class="text-left">Paper 1 Signed?</th>
<th class="text-left">Paper 2 Signed?</th>
<th class="text-left">Paper 3 Signed?</th>
</tr><br>';
while ($results = $query->fetch()) {
$ID = $results['ID'];
$Name = $results['Name'];
$paper1 = $results['paper1'];
$paper2 = $results['paper2'];
$paper3 = $results['paper3'];
echo '<tr>', //print the first column
'<td class="text-left">',$Name,'</td>'
//print the 3 remaining columns, depending on their values in the SQL table. If 1, show text. If not 1, print a submit button.
if ($question1 == '1') {echo "<td class=\"text-left\">Signed!</td>";}
else {echo "<form id=\"update\" method=\"POST\" action=\"\" ><td class=\"text-left\">
<input type=\"hidden\" id=\"field_update\" value=\"paper1\"/>
<input type=\"hidden\" id=\"ID\" value=\"" . $ID . "\"/>
<input type=\"submit\" id=\"submit\" onclick=\"saveData()\" value=\"Mark as Signed\"></form></td>" ;} //
if ($paper2 == '1') {echo "<td class=\"text-left\">Signed!</td>";}
else {echo "<form id=\"update\" method=\"POST\" action=\"\" ><td class=\"text-left\">
<input type=\"hidden\" id=\"field_update\" value=\"paper2\"/>
<input type=\"hidden\" id=\"ID\" value=\"" . $ID . "\"/>
<input type=\"submit\" id=\"submit\" onclick=\"saveData()\" value=\"Mark as Signed\"></form></td>" ;}
if ($paper3 == '1') {echo "<td class=\"text-left\">Signed!</td>";}
else {echo "<form id=\"update\" method=\"POST\" action=\"\" ><td class=\"text-left\">
<input type=\"hidden\" id=\"field_update\" value=\"paper3\"/>
<input type=\"hidden\" id=\"ID\" value=\"" . $ID . "\"/>
<input type=\"submit\" id=\"submit\" onclick=\"saveData()\" value=\"Mark as Signed\"></form></td>" ;}
echo "</tr>" ;
;
}
echo '</tbody></table></body></html>';
} else {
echo 'Nothing found';
}
Note the last three sections: this is where I print the last 3 columns of the table, showing if paper 1, paper 2 and paper 3 have been signed. If yes (=1), then I show the text "Signed!" If no (!=1), then I print an update button.
The update (submit) button is connected to a saveData() onclick function written in JQuery/AJAX.
<!-- function update -->
<script type="text/javascript">
function saveData(){
var field_update = document.getElementById("field_update").value;
var ID = document.getElementById("ID").value;
var dataString = 'field_update=' + field_update + '&ID=' + ID;
$.ajax({
type: "POST",
url: "update-ajax.php",
data: dataString,
cache: false,
success:function( html ) {
alert( html );
}
});
}
My issue is the following: the var values in the function are always going to the first row of values... this is because the field IDs for each column element in the table are the same.. so the function is always using the first set of results.
I could possibly run a loop to print a different javascript function for every row and cell... BUT that would be very inefficient.
I know there must be a better way, but scratching my head here. Any help would be much appreciated.
The reason why its taking the first row values is because the ids you are using are not unique. Since you are using jquery, you could do something like this.
$('input[type=submit]').on('click',function() {
});
This will attach this callback function to all submit button in the page. Now to know what values to use within the callback function, I suggest you use jQuery's data() function and data-* attributes. Something like this.
"<input type=\"submit\" id=\"submit\" onclick=\"saveData()\" value=\"Mark as Signed\" data-id=\". $ID. \"></form></td>" ;}
Note the data-id=$ID bit. Now you can access this id within the callback function using
$(this).data('id')
which will automatically get you the value of data-id attribute. No need of unique ids and jumping through hoops!
Prefix your id with an 'a_', 'b_', and 'c_' and you can easily split the javascript string to get the right id in your AJAX call.
As for unsolicited advice, learn a templating system, it will make your code much less difficult to read.

Getting value of multiple input boxes into multidimensional array using jquery

I have multiple input elements arranged in 16 rows and 5 columns (Just like a grid) . The contents of the 16 rows are inserted into a mysql table as 16 records with each record contains 5 fields. I want a method to get the value of all the input into an array using jquery and pass this to a ajax post request.
dataentry.php contains this code
jQuery('#metentry').submit(function(e){
e.preventDefault();
// getting data from form to variables
var date=jQuery('#stddate').val();
var kgsunit=jQuery('#unit').val();
var kgsshift=jQuery('#shift').val();
//sending data to script
jQuery.post("get_blank_form.php", {
"date":date,
'unit':kgsunit,
'shift':kgsshift,
}, function(data) {
//displaying message
jQuery('#blankform').html(data);
jQuery('#formpanel').hide();
});
get_blank_form.php contains this code:
echo'<form id="shiftentry" name="shiftentry" >';
echo "Date:<input id=shiftdate value='".$date."'/>";
echo "Unit:<input id=shiftdate value='".$unit."'/>";
echo "Shift:<input id=shiftdate value='".$shift."'/><br/>";
echo "<table><tr><th>No</th><th>Ele</th><th>Location</th><th>Drate </th><th>H3 Val </th><th>Part </th> <th>Iod</th><th>Cont. </th></tr>";
while($row2=mysql_fetch_array($result_sec))
{
echo "<tr>";
echo "<td>".++$rc."</td>";
echo "<td><input size='5' id='".$row2['ele']."' value='".$row2['ele']."' /></td>";
echo "<td><input id='".$row2['loc_id']."' value='".$row2['loc']."' /></td>";
echo "<td><input size='5' id='drate".$rc."' value='".$row2['drate']."'/></td>";
echo "<td><input size='5' id='h3".$rc."' value='0' /></td>";
echo "<td><input size='5' id='part".$rc."' value='0' /></td>";
echo "<td><input size='5' id='iod".$rc."' value='0' /></td>";
echo "<td><input size='5' id='cont".$rc."' value='0' /></td>";
echo "</tr>";
}
echo " </table>";
echo '<div align="center">';
echo '<input type="submit" id="submit2" name="submit2" value="Submit" width="30" />';
echo '</div>';
echo '</form>';
Both the above scripts are working and this will add a form"shiftentry" to the DOM in dataentry.php. This form conains around 21 rows and 8 columns containing input elements. I want a method to get the values in this 21 x 8 input elements and pass it to a jQuery post request. There are two issues.
Since the form is added after the DOM is loaded, how to get the value?
Is there any way to read all the input values using a loop instead of separate lines for each input element?
My final aim is to append this 21 rows into a mysql table. This part I knew, once I get all the values. Any suggestions ?
I have this function which create a multi dimensional array of input values. But in this casethe 'form1' is loaded before DOM is completed. But in the above scenario, form is dynamically added after DOM loding is completed
jQuery('#form1').submit(function(e){
e.preventDefault();
var arr = jQuery('#form1 tr:gt(0)').map(function() {
return [jQuery('input', this).map(function() {
return this.value;
}).get()];
}).get();
});
I also have another jquery script in this page which is used to traverse through the input boxes (obviously, these input boxes are loaded after DOM)
jQuery(document).delegate('input','keyup',function(e){
if(e.which==39)
jQuery(this).closest('td').next().find('input').focus();
else if(e.which==37)
jQuery(this).closest('td').prev().find('input').focus();
else if(e.which==40)
jQuery(this).closest('tr').next().find('td:eq('+jQuery(this).closest('td').index()+')').find('input').focus();
else if(e.which==38)
jQuery(this).closest('tr').prev().find('td:eq('+jQuery(this).closest('td').index()+')').find('input').focus();
});
How can I use the delegate option in the script used for traverse in the script for getting input values?
On form submit we can use $("#frmServiceMaster").serialize() to get the serialize string if you want JSON then use $("#frmServiceMaster").serializeArray()
It will convert all form input to String or JSON
$("#frmServiceMaster").submit(function(e){
event.preventDefault();
alert($("#frmServiceMaster").serialize());
alert($("#frmServiceMaster").serializeArray());
});
working FIDDLE

Send column name from button

I have made a php page. On which I am displaying table 'prod' from my data base.
each row is displayed nicely. Today i tried to add a button named 'rate' at the end of each row of my table. which I did successfully. Now I want to send the the value of the first column of that row to another php page when that button is clicked. I am stuck that how to do so? can you help please ??
I know i have to use the method post in my form and i have to use $_post[that value] on the other php page to inculcate the value for further function.
I just need to ask that where to add the value of my first column in the button line. so that onclick it can send that value. I hope I am clear over this. Thank You very much for help :)
<?php
include("connection.php");
$query = "select * from prod";
$res = oci_parse($conn,$query);
usleep(100);
if (oci_execute($res)){
usleep(100);
print "<TABLE border \"1\">";
$first = 0;
while ($row = #oci_fetch_assoc($res)){
if (!$first){
$first = 1;
print "<TR><TH>";
print implode("</TH><TH>",array_keys($row));
print "</TH></TR>\n";
}
print "<TR><TD>";
print #implode("</TD><TD>",array_values($row));
print "</TD></TR>\n";
echo "<td><form action='detailform.php' method='POST'><input type='submit' name='submit-btn' value='Rate'/></form></td></tr>";
}
print "</TABLE>";
}
?>
you have to add inputs in your form whatever kind u prefer
echo "<td>
<form action='detailform.php' method='POST'>
<input type='hidden' name='your_val_key' value='".$row[your_val_key_in_query]."'> <!-- input hidden, change to text 4 debug -->
<input type='submit' name='submit-btn' value='Rate'/>
</form>
</td></tr>";
and than, in your detailform.php u can get the val with
echo $_POST["your_val_key"];
if u are not sure how much data u send or somthing, try this and u get the full data:
echo "<pre>".print_r($_POST,true)."</pre>";
BTW: why are u mixing print and echo?
Use hidden input
echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='col-name' value='you-col-value'><input type='submit' name='submit-btn' value='Rate'/></form></td></tr>";

Input value invisible when set with php

PHP
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr>";
for($i=0;$i<7;$i++){
if($i==0){
echo "<td><input type='text' val='$row[$i]' /></td>";
}
if($i>1){
echo "<td>$row[$i]</td>";
}}echo "</tr>";
}
Except for the first column, which contains the input tag, everything comes out fine. The input tag shows up, but it appears empty--nothing to see, nothing to highlight. If I do 'inspect element', however, I see it has the correct value according to the output from the queried table.
Any thoughts as to what causes this strange behavior and how to fix it?
You have to use basic HTML Tag
You have to use "value" instead of "val"
See the Basic HTML Tag
<input type="text" value="Nikunj"/>
You should use value attribute instead of val:
echo "<td><input type='text' val='$row[$i]' /></td>";
-----------------------------^
should be:
echo "<td><input type='text' value='$row[$i]' /></td>";
-----------------------------^
Change val to value. val is not a valid attribute.
<input type='text' val='$row[$i]' />
--------------------^

Categories