Failing to send checkbox value to MySQL database? - php

I'm trying to store a Boolean value in my database based off a checkbox(Watched) in a form. If the checkbox isn't checked on form submit, it should send a 0; Otherwise a 1.
However, it sends a value of 0 no matter if it's checked or not. The Title Field and Genre field send perfectly, however the Watched conditional is not working correctly. I'm stumped and having a hard time wrapping my head around this, any thoughts?
<?php
require 'config/config.php';
require 'config/db.php';
// Check for Submit
if(isset($_POST['submit'])) {
// Get Form Data
$title = mysqli_real_escape_string($conn, $_POST['title']);
$genre = mysqli_real_escape_string($conn, $_POST['genre']);
if (isset($_POST['watched']) && ($_POST['watched'] == "value")) {
$watched = 1;
} else {
$watched = 0;
}
$query = "INSERT INTO movies(name, genre, watched) VALUES('$title', '$genre', '$watched')";
if (mysqli_query($conn, $query)) {
header('Location: '.ROOT_URL.'');
} else {
echo "ERROR: " . mysqli_error($conn);
}
}
?>
<form method="POST" action="<?php $_SERVER['PHP_SELF']; ?>">
<div class="md-form">
<input type="text" id="form1" class="form-control" name="title">
<label for="form1" class="">Title</label>
</div>
<div class="md-form">
<input type="text" id="form1" class="form-control" name="genre">
<label for="form1" class="">Genre</label>
</div>
<div class="form-group">
<input type="checkbox" id="checkbox1" name="watched">
<label for="checkbox1">Have you watched it already?</label>
</div>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</form>

You never set an actual value for the checkbox in your form HTML, so the value of the checkbox will never exist which means your if statement will always return false.
Simply change this:
<input type="checkbox" id="checkbox1" name="watched">
to this:
<input type="checkbox" id="checkbox1" name="watched" value="value">

Related

Problem: Part of the PHP exercise does not run correctly

I created a section for editing. When I edit the information and click the save button, the information is not saved and the header section does not display completely.
<?php
if (isset($_POST['submit_btn']))
{
$id = $_POST['id'];
$fn = trim($_POST['name']);
$ln = trim($_POST['lastname']);
$age = trim($_POST['age']);
$q = "UPDATE `users` SET `fn` = '$fn',
`ln` = '$ln',
`age` = '$age'
WHERE id = '$id'";
mysqli_query($dbconnect,$q);
if (mysqli_affected_rows($dbconnect) > 0)
redirect("?msg=ok&id=**$id**");
else
redirect("?msg=error&id=**$id**");
}
else
echo ("Not In If(isset)");
?>
<form action="" method="post">
<label for="name">FirstName:</label>
<input type="text" name="name" id="name" value="<?php echo $row['fn']?>">
<br>
<label for="lastname">LastName:</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $row['ln']?>">
<br>
<label for="age">Age:</label>
<input type="text" name="age" id="age" value="<?php echo $row['age']?>">
<br>
<input type="submit" name="submit_btn" value="Save">
<a href="index2.php">
Back
</a>
</form>
</body>
Bold sections do not work here.
Below is a picture of the result:
In the link that I specified, after clicking on save the ID will not be displayed and all the information filled in the forms will be lost.
Sorry if the result is styleless and boring and I just created this page to practice php😁
Thank you for being responsive🙏🙏🙏
You are mistaking a POST request with a GET request.
Part, which appears in the URL is sent to the webserver in GET request.
Your form is submitting POST request to the webserver, logic in the code does the same, but you are trying to display information from url (GET).
Please check the examples in php.net:
POST variables: https://www.php.net/manual/en/reserved.variables.post.php
GET variables: https://www.php.net/manual/en/reserved.variables.get.php
You can take an example with GET request variable below, however, be careful with trusting the "end client" and always prepare your statements, which you send to your database to execute queries.
if (isset($_GET['submit']))
{
$number = $_GET['number'];
echo $number
? "Number which was submitted: $number <br>"
: 'Number is not set';
} else {
echo 'Form has not been yet submitted';
}
?>
<form action="" method="get">
<input type="number" name="number" placeholder="Number">
<input type="submit" name="submit" value="Save">
</form>

Can´t update database with sent value

I can not update my database with sent variable "$id_zaznamu". I do not know why. If I use number, for example 5 or 4, it works. With variable "$id_zaznamu" doesn´t. But in the different examples with variabable $id_zaznamu everythning works correctly. In other words exactly the same variable "$id_zaznamu" works correctly in different situations, in this case not. It seems to me as if it is not integer, and it is. For any help I will be very thankful.
PHP:
$id_zaznamu=$_GET['id_zaznamu']; //get from different page
$error="";
if(isset($_GET['modify']))
{
$zadavatel=mysqli_real_escape_string($link,$_GET['zadavatel']);
$kontakt=mysqli_real_escape_string($link,$_GET['kontakt']); $somevalue=$_GET['someid'];
if(mysqli_query($link, "UPDATE zaznamy SET zadavatel='$zadavatel', kontakt='$kontakt' WHERE id_zaznam='$somevalue'"))
{
header("location:vypis.php");
}else
{
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
}
HTML:
<form method="GET" action="upravbyt.php"><br>
<label>Name:
<input type="text" name="zadavatel" class="field col-12" placeholder="Meno zadávateľa"/></label><br><br>
<label>Contact:
<input type="text" name="kontakt" class="field col-12" placeholder="Email"/></label><br><br>
<input type="hidden" name="someid" value="<?php $id_zaznamu=$_GET['id_zaznamu'];?>">
<input type="submit" name="modify" id="submit" class="btn" value="Upraviť"/><br><br>
</form>
You should add
<input name="id_zaznamu" value="...">

I am stuck while writing MySQL query to submit the content of a form which has text & checkbox

I have a form that had text and dropdowns. Now the client wants to use checkbox instead of dropdown. How to I change the query . Here is my code:
Form is in join.php
<form name="pantryinfo" id="pantryForm" method = "post" action="email.php" data-toggle="validator" role="form">
<label>Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Pantry Name" required>
<label>Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter Street address" >
<p class="help-block"></p>
<input type="checkbox" id="snapeligible" name="snapeligible" value="Yes">SNAP Eligilble<br>
<label>Community Meal?
select class="form-control" id="communitymeal" name="communitymeal" required >
<option></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</label>
<input name="submit" type="submit" id="submit" value="Add Food Provider" class="btn btn-primary center-block">
</form>
The field SNAP Eligilble was a dropdown just like Community Meal but now is a check box.
My earlier query was as follows in email.php
require 'config/connectDB.php';
//set variables from the form
$pname = $_POST['name'];
$paddress = $_POST['address'];
$psnapeligible = $_POST['snapeligible'];
$pcommunitymeal = $_POST['communitymeal'];
$sql = "INSERT INTO temp(pan_id, pname, paddress, psanpeligible, pcommunitymeal, )
VALUES(NULL,'$pname', '$paddress', '$psnapeligible', '$pcommunitymeal',)";
I am not sure how to append the query to include data from the check box only when the checkbox is selected as its not a required field.
An unchecked checkbox will not even be found in the $_POST array. This means to see from the PHP side whether the box was checked, all you have to do is look at whether the matching variable is set.
Change:
$psnapeligible = $_POST['snapeligible'];
To:
$psnapeligible = isset($_POST['snapeligible']) ? 'yes' : 'ho';
Make an IF-Statement, where you proof if the Value of the Checkbox is set.
Is it set use this Statement
Else use the another Statement without the psnapeligible
if (isset ($psnapeligible)) {
$sql = "...";
else {
$sql = "...";
}
you can chek in your php page (email.php) if your chek box is set or not ...
if (isset($_POST['snapeligible'])) {
$psnapeligible = $_POST['snapeligible'];
}
else {
$psnapeligible = "No" ;
}

how to get the submit button value which is in while loop using post method

Input field inside a while condition i'm displaying the tab in which tab values are fetched from table red_digid_info
<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');"">
<div class="row">
<label for="fromdate" class="col-sm-1 control-label"> FROM DATE </label>
<label for="todate" class="col-sm-1 control-label" style="margin-left: 4cm;"> TO DATE </label>
</div>
<div class="row">
<div class="col-sm-1">
<div class="input-group">
<input type="text" class="form-control" id="fromdatepicker" name="fromdate" placeholder="yyyy-mm-dd" style="width:200px;height:33px;">
<span class="input-group-addon"><i class='glyphicon glyphicon-calendar'></i></span>
</div>
</div>
<div class="col-sm-1" style="margin-left:4cm">
<div class="input-group">
<input type="text" class="form-control" id="todatepicker" name="todate" placeholder="yyyy-mm-dd" style="width:200px;height:33px;">
<span class="input-group-addon"><i class='glyphicon glyphicon-calendar'></i></span>
</div>
</div>
<div class="col-sm-offset-2 col-sm-2">
<input type="submit" value="ISP Status" class='btn btn-purple btn-rounded w-md m-b-5' name="isp_button">
<input type="hidden" value="1" name="pointer">
<button type="button" class="btn btn-pink btn-rounded w-md m-b-5" onclick="resetforms('form_isp_status')">Reset</button>
</div>
</div>
<div class="row">
<label for="isp" class="col-sm-1 control-label"> SELECT ISP</label>
</div><div class="row">
<div class="tab">
<?php
$isp_tab = mysql_query("SELECT DISTINCT(`isp`) FROM `red_dgid_info`");
while ($result = mysql_fetch_array($isp_tab)) {
$isp_value = $result[0];
echo '<input class="tablinks ion-social-rss" type="submit" name="isp_value[]" value="'.$isp_value.'">';
//echo '<input type="hidden" name="isp_hidden_value[]" value="'.$isp_value.'">';
}
?>
</div>
</div></form>
if i click any one value of a tab i ve to display the tab content so i need the value of submit button in php post method
if($_REQUEST['pointer'] ==1)
{
var_dump($_POST);
//-------status criteria given---------------------//
//-----------isp tab submiited--------------//
if(isset($_POST['isp_value']))
{
print_r($_POST['isp_value']);
$isp=$_POST['isp_value'];
}
//------------------end----------------------//
//----------hidden value array--------------//
/*$data = $_POST['isp_hidden_value'];
foreach($data as $isp)
{
echo "isp_hidden =".$isp;
}
//---------------another way----------------//
$isp_hidden = $_POST['isp_hidden_value'][$isp];*/
//--------------end------------------------//
$date= date("Y-m-d");;
$fromdatepicker =$_POST['fromdate'];
$todatepicker =$_POST['todate'];
exit;
}
if(isset($_POST['isp_value'])) //this if condition fails isp_value is not set don't know the reason and solution for it
submit function
function submit_isp_status(formId) {
if($("#"+formId).valid() == true) {
$.ajax({
type: 'POST',
url: 'webxstatus.php', //same page
data: $("#"+formId).serialize(),
success: function(data) {
..........
}
});
}
}
I'm stuck with this for past 2 days anyone help me to solve this.
you need to change your input name to array like this isp_value[] so only you can get the value which submit button you clicked otherwise you will get last value only .
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value[]' value='$isp_value'></input>"
PHP :
print_r($_POST['isp_value']);
And also minor single quotes problem in your isp_hidden_value
echo '<input type="hidden" name="isp_hidden_value[]" value="'.$isp_value.'">';
note:
if you need currently clicked submit button value means . don't use hidden field it will collect all values . just insert the value in submit button it will collect only curently clicked element value only as a array
Try this example :
<?php
if(isset($_POST['xyz']))
{
print_r($_POST);
}
?>
<form action="" method="post">
<input type="submit" name="xyz[]" value="1" >
<input type="submit" name="xyz[]" value="2" >
</form>
<?php $isp_tab=mysql_query("select distinct(isp) from red_dgid_info");
while($result=mysql_fetch_array($isp_tab))
{
echo'<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');">';
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'></input>";
echo '<input type="hidden" name="isp_hidden_value" value='$isp_value'>';
echo'</form>';
}?>
put form inside while loop
while($result=mysql_fetch_array($isp_tab))
{
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'></input>";
echo '<input type="hidden" name="isp_hidden_value[]" value='$isp_value'>';
}?>
$data =$_POST['isp_hidden_value'];
foreach($data as $isp)
{
echo "isp_hidden"=$isp;
}
Use input field 'isp_hidden_value' as array and fetch values using foreach
You need to do some changes in your code, and after that i hope it will work perfectly:
Change hidden field
from:
echo '<input type="hidden" name="isp_hidden_value" value="$isp_value">';
to:
echo "<input type='hidden' name='isp_hidden_value[$isp_value]' value='" . $isp_value . "'>";
In the post method change value assignment of hidden field
from:
$isp_hidden = $_POST['isp_hidden_value'];
to:
$isp_hidden = $_POST['isp_hidden_value'][$isp];
Rest should work fine.
Logic behind this change is to use array when using same name for multiple input types. Here you are using a flat variable which will hold only one value, which will get assigned at the end. If you use array it will hold multiple values and allows you to get your desired result.
You don't need a hidden field for this. A button with a name should send it's value.
<?php
var_dump($_POST);
?>
<form method="POST" action="">
<div class="row">
<div class="tab">
<input type="submit" name="button" value="test1">
<input type="submit" name="button" value="test2">
</div>
</div> </form>
Will tell me that $_POST['button'] is either test1 or test2
Which means that the following should work
<form method="POST" action="" id="form_isp_status" onsubmit="submit_isp_status('form_isp_status');"">
<div class="row">
<div class="tab">
<?php $isp_tab=mysql_query("select distinct(isp) from red_dgid_info");
while($result=mysql_fetch_array($isp_tab))
{
$isp_value =$result[0];
echo "<input class='tablinks ion-radio-waves' type='submit' name='isp_value' value='$isp_value'>";
// note: input is a empty tag, meaning that it is not to be closed using </input> but by using />, which
// is only relevant for XHTML
}?>
</div>
</div> </form>
Edit:
On the server side the only thing you have to do is use the value of $_POST['isp_value'].
var_dump($_POST); // only to check the POST variable during debugging
if (isset($_POST['isp_value'])) { // Possibly not needed if there are no other submit buttons in the from, but good practice to check if something exists
// do something using $_POST['isp_value']
}
As a sidenote: mysql_* has been deprecated in PHP 5.5.0 and been removed in PHP 7.0. It is recommended to either use MySQLi or PDO instead

form submission on product detail page

I have following code on the top of product detail page
<?php
include("include/connection.php");
session_start();
$ses_id = session_id();
$ID = (int)$_REQUEST['id'];
if (!isset ($_POST['submit']))
{
?>
<div class="row">
<div class="span9">
<div class="span6 ">
<h4>Review(0)</h4>
<p>There are no review for this product</p>
<h4>Write a Review</h4>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<p>Your Name:</p>
<input type="text" id="txtname" name="Rname" placeholder="write your name..." />
<p>Your Review</p>
Excelent<input type="radio" name="reviewbtn" class="radio" value="Excelent" />
Good<input type="radio" class="radio" name="reviewbtn" value="Good" />
Poor<input type="radio" class="radio" name="reviewbtn" value="Poor" /><br/>
<textarea id="txtreview" name="txtbx" cols="50" rows="10"
class="container-fluid"></textarea>
<input type="submit" value="submit" class="btn" />
</form>
</div>
</div>
</div>
<?php
} else {
$Rname = mysql_real_escape_string(stripslashes(htmlentities($_POST["Rname"])));
$Reviewbtn = $_POST["reviewbtn"];
$Txtbox= mysql_real_escape_string(stripslashes(htmlentities($_POST["txtbx"])));
$sql=mysql_query ("INSERT INTO reviews (Name, Comments,Rating) VALUES('$Rname','$Reviewbtn','$Txtbox')", $con) or die (mysql_error());
echo "Record added succesfully. You will be redirected to previous page in 5 seconds";
header( "refresh:5;url= product_detail.php" );
}
mysql_close($con);
?>
here I am getting error
Notice: Undefined index: id in \product_detail.php on line 5
( which is $ID = (int)$_REQUEST['id']; )
basically I am building a rating form on a product,please if someone can modify the code so form submission could be done using ajax jquery call so page should not load again
remove int from it there no need of it.
$ID = $_REQUEST['id'];
There is no Element named ID in your form
So when you are going to catch this it occurred error
$ID = $_REQUEST['id'];
^ provide actual form element's name here
When you coming to this page from previous page it is not showing error
after submitting from it is showing error.
If it is, add an hidden element into your form
<input type='hidden' name='id' value="<?php echo $ID; ?>">
It will solve the problem
Use some other word as name attribute rather than naming it as id you can set it to user_id or something else you want,because it is not a good practice
if(isset($_REQUEST['user_id'])){
$ID = $_REQUEST['user_id'];
}

Categories