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
Related
Why isn't my form working and why are there no errors showing? When I click the submit button nothing happens, here is my code:
<?php
$list_of_product=$p->loadSearchProduct($searchkey);
foreach ($list_of_product as $product) {
echo "<tr>"
.'<form id ="myForm" action = "InsertOrders.php" method = "POST">'
."<td>".$product->prodname."</td>"
."<td>".$product->price."</td>"
."<td>".$product->total." "."Piece(s)"."</td>"
."<td>".$product->remaining_stock." "."Piece(s)"."</td>"
."<td>".$product->sold_stock."</td>"
."<td>"."<input class='form-control' name='qty' type='text' required/>"."</td>"
."<td>"."<button type='submit' id='sub' class='btn btn-primary'>"."<b>Add to List</b>"."</button>"."</td>"
."</form>"
."</tr>";
}
?>
In this case you have several forms with the same id.
When you click submit, it es not specific witch one is clicked.
EDIT
$count = 0;
foreach ($list_of_product as $product) {
echo "<tr>"
.'<form id ="myForm" action = "InsertOrders.php" method = "POST">'
."<td>".$product->prodname."</td>"
."<td>".$product->price."</td>"
."<td>".$product->total." "."Piece(s)"."</td>"
."<td>".$product->remaining_stock." "."Piece(s)"."</td>"
."<td>".$product->sold_stock."</td>"
."<td>"."<input class='form-control' name='qty' type='text' required/>"."</td>"
."<td>"."<button type='submit' id='sub".$count."' class='btn btn-primary'>"."<b>Add to List</b>"."</button>"."</td>"
."</form>"
."</tr>";
$count++;
}
When you use an counter, you can check in you InsertOrders.php which one is clicked. Its not the best way, but it will be work.
i think if you can use form tags outside of the foreach, it will submit. Or else try remove 'id' attribute in your code.
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.
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>";
<?php
require "../db/dbconfig.php";
$gal=mysql_query("select * from gallery");
$numrows=mysql_num_rows($gal);
if($numrows>=1)
{
echo "<form action='delete.php' method='post' name='f2' id='f2'>";
echo '<table id="rqst" style="display:block;" border="0" cellpadding="12" cellspacing="3" width="500px">';
echo "<tr><th>Tick to select</th><th>Images in Gallery</th></tr>";
while($row=mysql_fetch_array($gal)
{
$imgfile=$row['ImgName'];
$Image="<img src=gallery/".$imgfile." width='230px' height='150px'/>";
$img_name=$imgfile;
echo "<tr>";
echo "<td><input type='checkbox' name='imgs[]' value='$img_name'></td><td>".$Image."</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td colspan='3' align='right'>";
echo "<input type='submit' value='Delete' name='del'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
?>
This is my code....This will display images from gallery and checkboxes associated with them. When I click delete button with unchecked checkboxes an alert should come like this "Please check at least one checkbox"..How to do that??
My next problem is,,when I click delete button after checked checkbox, alert should come like this=" Do you want to delete?? "...If clicked Ok,the image must be deleted else do nothing...Please help ...Thanks in advance....
check this below link for validation using jquery:
http://jsfiddle.net/susheel61/U3Unk/2/
<form id="form">
First name: <input type="checkbox" name="firstname" class="check"><br>
<button>test</button>
</form>
$("button").on("click",function(e){
var status = $(".check").is(":checked");
e.preventDefault();
if(!status){
alert("this is not checked");
}
});
Yes, you can do it by javascript or jquery to validate whether your atleast one checkbox is select or not. So, for that you need to give a common class for all checkbox as example
<input type="checkbox" name="firstname" class="addchk">
Now in your submit button call a javascript function which validate the matter.
<input type='button' value='Delete' name='del' onclick='delete_checked()' />
Now write a function to validate whether any checkbox is selected.
function delete_checked()
{
var status = $(".addchk").is(":checked");
e.preventDefault();
if(!status){
alert("this is not checked");
}
else
{
// SUbmit yout form
}
}
I have the following that is generate for every record in my database
$allbills = mysql_query("SELECT * FROM outgoings WHERE outgoings.user_id = '$uid'") or die(mysql_error());
echo "<table>";
while($info = mysql_fetch_array( $allbills ))
{
echo "<tr>";
echo "<th>bill id:</th> <td>".$info['id'] . "</td> ";
echo "<th>total:</th> <td>".$info['bill'] . "</td> ";
echo "<th>bill name:</th> <td>".$info['bill_name'] . "</td> ";
echo "<th>bill deposit:</th> <td>".$info['bill_description'] . "</td> ";
echo "<th>colour:</th> <td>".$info['bill_colour'] . " </td>";
echo "<th>edit:</th> <td>
<form class='bill-upd'>
<input type='hidden' value='".$info['rand']."' name='rand2' id='rand2'>
<input type='hidden' value='".$info['id']."' name='billid' id='billid'>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' class='bill-upd-submit' />
</form>
</td>";
echo "</tr>";
}
echo "</table>";
This updates my users record in a table using AJAX
$(document).ready(function(){
$(".bill-upd-submit").click(function() {
var elem = $(this);
$.post('update_bill.php', elem.parent('.bill-upd').serialize(), function(data) {
elem.append(data);
});
});
});
Once this is done however, the user needs to refresh the page to see the results, is there a way I can populate the table the user edits, with the latest data after the update query takes place?
I would try a different approach:
1) Add an invisible div right after your button. You can do this dynamically:
$(document).ready(function() {
$(".bill-upd-submit").after("<div style='display:none'></div>");
// ...
});
2) Now your post event would be as follows:
$(".bill-upd-submit").click(function() {
var elem = $(this);
$.post("update_bill.php", elem.parent(".bill-upd").serialize(), function(data) {
elem.next("div").html(data);
});
});
BTW, I'm assuming that there are other buttons in the same page, and that's the reason for using class (bill-upd-submit) instead of id. If there is just one button, id is faster. Also, I think that bill-upd-submit is of type button. If it is type submit, I would change-it to button or added the following to the click event:
function() {
// ... the code shown above
return false;
});
This will prevent the form's submit to happen.
Looks to me like your current javascript is trying to append the form, not the table. If you're trying to add a row to the table at the bottom and keep all the other rows, then this might work. Give your table an ID in the html markup (here I use "table_id"):
$(".bill-upd-submit").click(function() {
$.post("update_bill.php", elem.parent(".bill-upd").serialize(), function(data){
$("#table_id tr:last").after(data);
});
});
And just make sure your php file (update_bill.php) has the appropriate html built into it to echo a proper tr for you.