Here is HTML/JavaScript:
<form method = "post" style="display: inline;" name="thisform<?php echo $employee->id; ?>">
<input type="hidden" name="user" value="<?php echo $employee->id; ?>" />
<input type="hidden" name="auto" value="<?php echo $employee->stay_live; ?>" />
<h3><input type="checkbox" name="stay_live" onclick="document.forms.thisform<?php echo $employee->id; ?>.submit();" <?php if ($employee->stay_live == '1') { echo "checked"; } ?> title="Click to Stay Live Every Day" /> <?php echo $employee->name; ?>
</form>
Here is PHP:
<?php
if(isset($_POST['stay_live'])) {
$user=$_POST['user'];
$auto=$_POST['auto'];
if ($auto == 1) {
$sql = "UPDATE users SET stay_live = 0 WHERE id = '{$user}';";
}
if ($auto != 1) {
$sql = "UPDATE users SET stay_live = 1 WHERE id = '{$user}';";
}
mysqli_query($dbconnection, $sql);
}
?>
If you see the onclick code in the form, it will auto-submit form and do PHP POST. However, the onclick only works if the checkbox is NOT checked. If it IS checked, the screen does refresh, as if it did thing, but the POST is never submitted.
So to summarize; everything works as expected when the box is not checked and it needs to be set. But to UNSET it, the server function is never called. Can anyone see why?
note: this is test code, so please no comments on sql injection
Checkbox values are not sent when they are unchecked, so $_POST["stay_live"] is not set.
<?php
if (isset($_POST["user"])) // type="hidden" will be sent regardless of checkbox
{
if (isset($_POST["stay_alive"])) echo "Checkbox checked";
else echo "Checkbox not checked";
}
?>
Using Jquery I'd do the following: You need to make a file with the functions that you want to be executed. This file will receive via POST or GET
To your onclick attribute just add an if for your action variable, if(element checked) action = unchecked --- else action = check
--Jquery function
function cBoxSubmit($employId, $action){ // call it in your onclick attribute.
$.post("submitFunction.php",{action: $action, employId: $employId, ...},function(data){ // Parameters: URL file, variables which will receive, call back function
if(data){
// On Success or in your case if checked
// add some code if needed
}
else{
// If unchecked
// add some code if needed
}
}
}
NOTE: echo == return in your php file ... This is how you return data to the call back function in your Jquery function
Related
At the moment, I'm using a loop to read the 'questions' and 'answers' fields from my postgresql "PDPC".considerations table and reflecting them on the form. I'd like to update them all with one submit button.
I refered to PHP MySQL Multiple Forms and Multiple Submits on single page and tried using the <input type="hidden">, arrays and while loop but the form either does not execute or it does not correctly update all the forms.
I think the error is around the $_POST (at the top) and the HTML form (at the bottom). (Sorry if the codes are messy, it is my first time with PHP, HTML and Postgres). Thank you!
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
// Processing form data when form is submitted
if(isset($_POST["consideration_no"]) && !empty($_POST["consideration_no"])){
$counter = 0;
// Get hidden input value
//$consideration_no = $_POST['consideration_no'];
$dg_no = $_POST['dg_no'];
$consideration_no = $_POST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
while ($counter<5){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer1[$counter] = $input_answer;
}
// Prepare an update statement
$sql = 'UPDATE "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//Set Parameter
$param_answer = $answer1[$counter];
$param_consideration_no = $consideration_no[$counter];
// Attempt to execute the prepared statement
$stmt->execute();
$counter++;
}
}
if($stmt->execute()){
// Records updated successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1)';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Collection Purpose Section
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
echo "<a href='considerationupdate.php?consideration_no=". $row['consideration_no'] ."' title='Update Data Map' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>";
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
<input type="hidden" name="consideration_no[]" id = "consideration_no" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<?php
}
?>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
It should read the questions and answers from the DB table, show it on the forms as the label and text fields (working), and the user should be able to update the form after editing the text fields and clicking submit (Not working properly).
Since is your form and you are using SQL to get and the objective is to update the data with one submit?
Why not just use one form?. I belive you can do all you need with just one and multiple input.
Your branch if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){ depends on get parameters, however, your <form method="post"> of <input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/> uses post parameters.
Therefore the branch will never be executed unless the page is requested by another GET-request like a link or another form.
If the parameters can occur in both methods, POST and GET as well, you might want to check the $_REQUEST array instead. Be aware that the parameters listed in $_REQUEST can vary depending on the .ini settings request_order and variables_order.
According to your comment 'Because each form is for one table row.' in another answer, this might be an XY problem.
Consider to take the common way not generating multiple forms but array parameters similar as you did in
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
Here you rely on keys getting generated automatically. As well you can specify an individual key:
<input type="text" name="some_parameter[<?php echo $answer; ?>]">
Further more
There is an HTML line in the loop having a static id on an element:
<input type="hidden" name="consideration_no[]" id="consideration_no" value="<?php echo $consideration_no; ?>"/>
This will not break PHP, however, it is against the HTML specs saying an id has to be unique per document.
I have fixed the issue! It was the logical flow of the script. Specifically, the POST variable at the top should be changed to dg_no, add the dg_no parameters along with it, loop the parameters instead of the entire preparation script and include the execute script in the whie loop too.
Thanks for the help and guidance, they were much appreciated!
I have a code like this
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
} else {
echo "wrong";
}
?>
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
I want to save values into db after user clicks the submit button. I have been trying different approaches, but still could not get near to it.
Any ideas/hints what I should do next or doing wrong?
After the given suggesstion below is my code :
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
<?php
if(isset($_REQUEST['submit1']))
{
echo "$thismemberinfo[msurf]";
echo " $msurfclicks";
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
//$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo " not set " ;
}
}
?>
you can use isset for checking if button is clicked or not
if(isset($_REQUEST['submit1']))
{
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
header("location:".$_SERVER['PHP_SELF']);
}
You need to check if the request has come from the post submit i.e. as others pointed check $_POST['submit']
if(isset( $_POST['submit'] ) {
// your complete rest php code goes here to insert the record
}
On page refresh, it'll see the request is not a post request submitted hence won't execute the php code in the if and will just display the page.
Your code is missing a few things..
To insert entries into the database, you should think more about what tasks need to be carried out, I'll give you a list of them, you have probably done some of these.
1) Connect to the database.
2) Obtain the values entered into the form, and store them in local variables, in your case you have used POST on your form and therefore.. here's an example:
$Field1 = mysql_real_escape_string($_POST['match']); // match?? This post data comes from the name field of your form.
3) Create your query... e.g..
$sql = "INSERT INTO table_name (table_heading) VALUES ('$Field1')";
4) Run the query
I have a form that includes a delete button. I want the user to be able to select all the items they wish to delete at once.
I managed to get the echo to display but the items still remain on the page. Can you please point out why that happens? Any help is appreciated!
Delete button:
<input name="del_btn" type="submit" value="Delete">
The check:
if (isset($_POST['del_btn']) && $_POST['del_btn']){
for($i = 0; $i < count($_POST['checkbox']); $i++){
if (isset($_POST['checkbox'])) {
mysql_query("DELETE FROM `posts` WHERE `id` = '" . $_POST['checkbox'][$i] . "' LIMIT 1");
echo 'deleted';
}
}
}
the items' checkbox:
<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />
This really depends on how variables are defined in your controller, and how they are displayed in your view file.
If you want to hide/clear the values in your forms you can:
Reload the page: create a redirect at the end of your if (isset($_POST['del_btn']) && $_POST['del_btn']){ statement that sends the user back to the new page.
Use jQuery to hide divs where the checkbox is checked.
Redefine variables in your controller after the post to be NULL.
Add a ternary operator to your values in the view so for example <input name="form_input" type="text" value=<?=isset($_POST['del_btn'] ? NULL : $form_input?>> which means that the form will display as NULL when the del_btn is submitted.
<input name="checkbox[]" type="checkbox" id="<?php echo $id; ?>" />
I think you must put something like
<input name="checkbox[]" type="checkbox" value="<?php echo $id; ?>" />
Note the word "value" instead of "id". You are putting the ID in the id attribute. It is to assign a specific target if you want to take the value. (You can use Javascript or JQuery to do this).
In your case, use the tag "value" to ensure that you have correct ID value for your check box. Echo the query and not the word "deleted".
$queryDel = "DELETE FROM posts WHERE id = " . $_POST['checkbox'][$i] . " LIMIT 1";
echo $queryDel;
Please beware of SQL Injection if you are using mysql_query(). Use mysqli instead. Use prepared statement to prevent it or at least provide some white list or validation.
Hope this helps. Thank you.
<input name="checkbox[]" type="checkbox" value ="<?php echo $id; ?>" id="<?php echo $id; ?>" />
Try this it will work. and check the value print_r($_POST) you will able to see all the post value and able to get right value.
When you are using checkbox your element became an array than you can use multiple approaches:
Use ajax (example with jQuery) to avoid submit:
<script>
$(document).ready(function() {
$('[name="del_btn"]').click(function() {
$.post('/my/action.php', $('form').serialize(), function(r) {
if (r.success) {
alert('deleted....');
} else {
alert('error');
}
},'json');
return false; // prevent submit
});
});
</script>
Than you can simplify your code with this:
<?php
if (isset($_POST['checkbox']) && count($_POST['checkbox'])){
$c = implode(',', array_map('intval', $_POST['checkbox'])); // sanitize data
$r = mysql_query("DELETE FROM `posts` WHERE `id` IN(" . $c .")");
echo json_encode(array('success' => $r));
}
As the title reveals I got an issue with how to update a checkbox that already has data in my SQL database.
My code looks like following:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name <input type"text" name="inputName" value="<?php echo $hemsida['Namn']; ?>" /> </br>
Commentar <input type"text" name="inputComment" value="<?php echo $hemsida['Comment']; ?>" />
<br/>
</br><input type="checkbox" name="inputAll" value="checked" <?php echo $hemsida['All']; ?>/>Alla
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Redigera">
<?php
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$_POST[inputALL]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php");
}
?>
The echo $hemsida['Namn'],['Comment'], and ['All'] just brings up and shows the old data thats in the database, but I do not understand what to do to update the checkbox. I have looked everywhere but I am stuck. Thank you in advance!
If I understand your question correctly, you are looking for a way to have a checkbox be either checked or not checked depending on database info. If so, I would try something like this. At the top of your code where you get your database info, put
if($conditionForCheck){
$inputAll = ' checked="checked"';
}
Then in your form
<input type="checkbox" name="inputAll"<?php echo $inputAll; ?> />
your question is not clear but i think you have a column in your database named "all" ? and perhaps this column can take only 1 value (true or false) !!
then you can test this value in your form, if the value is true : checkbox will be checked, else : checkbox will not be checked :
<input type="checkbox" name="inputAll" checked="<?php if($hemsida['All'] == true) echo checked; ?>" />Alla
dont use value="", use checked instead, then test value of $hemsida['All'] if it's true echo checked else anything to do
for your php code and server side of your application you can just test if checkbox is checked and then you have choice for what do you want to assign to your column in database, for example if checkbox is checked create a variable (for example $value_of_checkbox) and assign a value ("true" for exampel) to this variable, then include this variable in your sql code for update database column :
if (isset($_POST['inputALL'])) {
$value_of_checkbox = true;
}
else {
$value_of_checkbox = false;
}
if(isset($_POST['submit'])) {
$u = "UPDATE hemsida SET `Namn`='$_POST[inputName]', `Comment`='$_POST[inputComment]', `ALL`='$value_of_checkbox' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User has been modified";
header("Location: ..//sokh.php")
note : i change also sql code in this part : ALL='$value_of_checkbox'
I'm doing a site with a voting system. What i want is to disable all input buttons (the ability to vote) if the user isnt logged in (ie. a session doesnt exist). How do i do a check in PHP at the top of the page and then allow/disallow the input buttons? Would i use CSS or jQuery?
Somewhere in the code check if the session is not set:
if(!isset($_SESSION['some_key'])){
$disable = true;
}else{
$disable = false;
}
Then, in the html:
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 1
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 2
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 3
But you still have to check at the serverside before you accept the vote, if the person has voted before, because this form can be edited easily to post the data again and again.
<?php if(!isset($_SESSION['logged']))
{
echo "<script language=\"javascript\">";
echo "$(document).ready(function()
{
$('input[type=submit]').each(function() { this.attr('disabled', 'disabled') });
});</script>"
}
?>
You should dynamically generate a correct HTML code. Something like this:
<?php if(isset($_SESSION['logged'])): ?>
<form> voting form </form>
<?php else: ?>
<p>Sign in to vote</p>
<?php endif ?>
You should also check whether user is logged in before you process a form:
if (isset($_SESSION['logged']) && isset($_POST['vote'])) {
// process form
}