I have a settings page as a part of my game for class and one of the settings fields is a checkbox.
This is my HTML field for the checkbox:
<div class="field">
<label for="allow_robot_name">Allow Robot Name?</label>
<input type="checkbox" name="allow_robot_name" <?php if ($r->allow_robot_name == 1) { echo "checked"; } ?>>Yes
</div>
The issue I am having is when the user checks the checkbox the value in the database changes to 1. However if they then uncheck it and then update the database the checkbox resets to checked and the value doesn't change from 1 to 0.
This is my code for updating the database:
<?php
$records = array();
if (!empty($_POST)) {
if (isset($_POST['site_name'], $_POST['header_text'], $_POST['footer_copyright'], $_POST['default_robot_name'])) {
$site_name = $_POST['site_name'];
$header_text = $_POST['header_text'];
$footer_copyright = $_POST['footer_copyright'];
$default_robot_name = $_POST['default_robot_name'];
if (isset($_POST['allow_robot_name'])) {
$allow_robot_name = 1;
} else {
$allow_robot_name = 0;
}
if (!empty($site_name) && !empty($header_text) && !empty($footer_copyright) && !empty($allow_robot_name) && !empty($default_robot_name)) {
$update = $db->prepare("UPDATE user_settings set site_name = ?, header_text = ?, footer_copyright = ?, allow_robot_name = ?, default_robot_name = ?");
$update->bind_param('sssis', $site_name, $header_text, $footer_copyright, $allow_robot_name, $default_robot_name);
if ($update->execute()) {
header('Location: index.php');
die();
}
}
}
}
Why doesn't the checkbox value update?
It's due to !empty($allow_robot_name).
empty($x) means !isset($x) || $x == null. Since 0 is considered equivalent to null in PHP, empty($allow_robot_name) will evaluate to true, if the checkbox is left unchecked, and your update query is not executed.
Related
I am working on a project where I need to read in users (am using MySQL) and be able to sort 1. Men/Women 2. Salary (eg. 30k+, 50k+, 100k+...)
I've tried setting up a select dropdown but for some reason it's showing only the men, even if I select women.
<form action="#" method="post">
<select name="Gender">
<option value=''>Select Gender</option>
<option value="Men">Men</option>
<option value="Women">Women</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
if(isset($_POST['submit']) && $_POST['submit'] = "Men"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
elseif (isset($_POST['submit']) && $_POST['submit'] = "Women"){
$selected_val = $_POST['Gender'];
echo "You have selected :" .$selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while($row = $result->fetch_assoc()) {
//Prints user data
}
}
else {
while($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
}
else {
print("-");
}
You've assigned the values in the ifs instead of comparing against them. Also, you've used the wrong input to compare against. $_POST['submit'] will always contain the value Get Selected Values.
if (isset($_POST['submit']) && $_POST['Gender'] === "Men") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Man'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} elseif (isset($_POST['submit']) && $_POST['Gender'] === "Women") {
$selected_val = $_POST['Gender'];
echo "You have selected :" . $selected_val;
$conn = create_Conn();
$sql = "SELECT * FROM users WHERE kon='Woman'";
$result = $conn->query($sql);
if (isset($_SESSION['anvnamn'])) {
while ($row = $result->fetch_assoc()) {
//Prints user data
}
} else {
while ($row = $result->fetch_assoc()) {
//Prints user data but emails
}
}
} else {
print("-");
}
Here's the code a little more simplified and less redundant. And under the assumption that you're using PHPs PDO.
if (strtolower($_SERVER['REQUEST_METHOD']) === 'post') {
$gender = $_POST['Gender'] ?? null; // your old $selected_val variable
if (!$gender) {
// do something to abort the execution and display an error message.
// for now, we're killing it.
print '-';
exit;
}
/** #var PDO $dbConnection */
$dbConnection = create_Conn();
$sql = 'SELECT * FROM users WHERE kon = :gender';
$stmt = $dbConnection->prepare($sql);
$stmt->bindParam('gender', $gender);
$stmt->execute();
foreach ($stmt->fetchAll() as $user) {
if (isset($_SESSION['anvnamn'])) {
// Prints user data
} else {
// Prints user data but emails
}
}
}
As Dan has provided a grand answer prior to mine, this is now just a tack on for something to review.
If you look at your form you have two elements.
On Submission, your script will see..
Gender - $_POST['Gender'] will either be '', 'Men', or 'Women'
Submit - $_POST['submit'] will either be null or the value "Get Selected Values".
It can only be null if the php file is called by something else.
You can see this by using the command print_r($_POST) in your code just before your first if(). This allows you to test and check what is actually being posted during debugging.
So to see if the form is posted you could blanket your code with an outer check for the submit and then check the state of Gender.
The following has the corrections to your IF()s and some suggestions to also tidy up the code a little bit.
<?php
// Process the form data using Ternary operators
// Test ? True Condition : False Condition
$form_submitted = isset($_POST['submit'])? $_POST['submit']:FALSE;
$gender = isset($_POST['Gender'])? $_POST['Gender']:FALSE;
if($form_submitted){
if($gender == 'Men') {
// Stuff here
}
else if($gender == 'Women') {
// Stuff here
}
else {
print("-");
}
} else {
// Optional: Case where the form wasn't submitted if other code is present.
}
You could also consider using the switch / case structure. I'll leave that to you to look up.
I got a problem this is simple form i have to submit the data through radio buttons problem is that no value is displayed in database neither of disases name nor for yes,no option I have created database with name doctor with fields id ,dis_name,and ans.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
if (!empty($_POST)) {
// keep track validation errors
$disError = null;
$ansError = null;
// keep track post values
$dis_name = isset($_POST['dis_name']);
$ans=isset($_POST['ans']);
// validate input
$valid = true;
if (empty($dis_name)) {
$disError = 'Please enter Diseases Name';
$valid = false;
}
if (empty($ans)) {
$ansError = 'Please check one of option';
$valid = false;
}
// insert data
if ($valid) {
if(isset($_POST['dis_name'])){
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO diseases (dis_name) values(?)";
$q = $pdo->prepare($sql);
$q->execute(array($dis_name));
Database::disconnect();
//header("location: diseases.php");
}
}
}
?>
//some html code here
<div class="control-group <?php echo !empty($ansError)?'error':'';?>">
<label class="check">Have you suffered pain preiviously???</label>
<div class="controls">
<input type="radio" name="choice" <?php if (isset($ans) && $ans=="yes") echo "checked";?>
value="Yes">Yes
<input type="radio" name="choice"<?php if (isset($ans) && $ans=="no") echo "checked";?>
value="No">No
<?php
//if(isset($_POST['submit'])){
if(!empty($_POST['choice'])){
$ans=isset($_POST['ans']);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO diseases (question) values(?)";
$q = $pdo->prepare($sql);
$q->execute(array(isset($_POST['choice'])));
Database::disconnect();
}
//}
?>
`isset() it gives undefined index warning.`
I suppose ans stands for answer which is filled by the radio control value. And this is how you fetch it on server side:
$ans=isset($_POST['ans']);
In your html it is actually choice
Shouldn't you be getting it like this?
$ans=isset($_POST['choice']);
EDIT:
And why would you use isset function to fetch post value?
isset() returns boolean and the input is named 'choice'.
Perhaps you mean:
if( isset($_POST['choice']) ){
$ans = $_POST['choice'];
// Optionally you may want $ans to be boolean:
if($ans == 'Yes') {
$ans = TRUE;
} else {
$ans = FALSE;
}
}
then (if the table column is properly defined to store the boolean/integer/enum):
$q->execute(array($ans));
will store 1 (True) or 0 (False)
I have this script that checks a submitted form. It checks if all fields are all filled out, and checks if the user has submitted the form before. It also checks if the entered data is already in the database or not. When I try to check if the entered data is in the database, it always returns false. My question is: How can I efficiently check if the POST values are the same?
Code:
<?php
error_reporting(E_NOTICE ^ E_ALL);
$Name = $_POST['name'];
$ID = $_POST['id'];
$Topic_1 = $_POST['1'];
$Topic_2 = $_POST['2'];
$Topic_3 = $_POST['3'];
$Topic_4 = $_POST['4'];
$Topic_5 = $_POST['5'];
$Topic_6 = $_POST['6'];
$Topic_7 = $_POST['7'];
$Topic_8 = $_POST['8'];
$Topic_9 = $_POST['9'];
$Topic_10 = $_POST['10'];
$Topic_11 = $_POST['11'];
$Topic_12 = $_POST['12'];
$Topic_13 = $_POST['13'];
$Topic_14 = $_POST['14'];
$Topic_15 = $_POST['15'];
$IP = $_SERVER['REMOTE_ADDR'];
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Check = 'SELECT * FROM Submissions WHERE School_ID = "'.$ID.'" AND IP = "'.$IP.'"';
$Insert = 'INSERT INTO Submissions (Name, School_ID, Topic_1, Topic_2, Topic_3, Topic_4, Topic_5, Topic_6, Topic_7, Topic_8, Topic_9, Topic_10, Topic_11, Topic_12, Topic_13, Topic_14, Topic_15, IP) VALUES ("'.$Name.'", "'.$ID.'", "'.$Topic_1.'", "'.$Topic_2.'", "'.$Topic_3.'", "'.$Topic_4.'", "'.$Topic_5.'", "'.$Topic_6.'", "'.$Topic_7.'", "'.$Topic_8.'", "'.$Topic_9.'", "'.$Topic_10.'", "'.$Topic_11.'", "'.$Topic_12.'", "'.$Topic_13.'", "'.$Topic_14.'", "'.$Topic_15.'", "'.$IP.'")';
if($Name && $ID != "")
{
if($Result = $Connect->query($Check))
{
$Rows = $Result->num_rows;
if($Rows == 0)
{
if($_POST != $_POST)
{
if($Go = $Connect->prepare($Insert))
{
if($Go->execute())
{
echo 'Thanks';
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'There Was An Error';
}
}
else
{
echo 'No Two Values Can Match.';
}
}
else
{
echo 'You Cant Vote Twice.';
}
$Result->close();
}
else
{
echo 'There Was An Error.';
}
}
else
{
echo 'Please Fill Out All Fields';
}
$Connect->close();
Your if statement should look like
if($name != "" && $check != "")
Here's the error:
if($_POST != $_POST)
You do probably want to compare the result from the db with the $_POST instead.
$Row = $Result->fetch_assoc();
if($Row != $_POST)
Prior to doing a comparison use var_dump() on the variables to check what they actually contain.
var_dump($Name);
var_dump($ID);
exit();
Then check for a negative or positive match.
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
You can even spoof that in a separate file.
<?php
$Name = 'Bob';
$ID = ''; // or use 0 or any test you want
var_dump($Name);
var_dump($ID);
if( !empty($Name) && empty($ID) ){
exit('ah, name filled in but not id ...');
}
Isolating problems like this will help you develop incrementally, get something working, then add more lines till you arrive at your destination.
To check if not two POST values are the same:
array_diff($_POST, array_unique($_POST));
What you looking for is following
$_POST['1'] = 'a';
$_POST['2'] = 'b';
$_POST['3'] = 'c';
$_POST['4'] = 'a';
$_POST['5'] = 'd';
$results = array_unique($_POST);
var_dump($results);
returns:
array
1 => string 'a' (length=1)
2 => string 'b' (length=1)
3 => string 'c' (length=1)
5 => string 'd' (length=1)
You can't really so easily check if a person did submit a form before.
One way is to add one more hidden field to form if the request came with POST.
Something like that:
<form method="POST" action="">
<?php
if(isset($_POST['submit'])) {
echo '<input type="hidden" name="second_post" value="1">';
} ?>
<!-- Other form items -->
<input type="submit" name="submit" value="1">
</form>
Then you can check is it a second time with:
if(isset($_POST['second_post'])) {
// Second time of form post;
} else {
// First (or zero) time post.
}
I have a fairly general problem. I have a small form
<form action="<?=base_url();?>ticket/close_ticket/<?=$ticket_details['id'];?>" method="post" id="close_ticket" name="close_ticket">
<ul>
<li><label for="frm_status">Status<span class="req">*</span></label>
<span class="input">
<select id="frm_status" name="status" onchange="this.form.submit()">
<option value="<? if ($ticket_details['status'] == "Open") $status= "1"; else $status= "2"; echo $status;?>"><? if ($ticket_details['status'] == "Open") $status= "Open"; else $status= "Closed"; echo $status;?></option>
<option value="<? if ($ticket_details['status'] == "Open") $status= "2"; else $status= "1"; echo $status;?>"><? if ($ticket_details['status'] == "Open") $status= "Closed"; else $status= "Open"; echo $status;?></option>
</select>
</span>
</li>
</ul>
</form>
This form contains the drop list option box, that on change submits the form to the close ticket controller......
public function close_ticket()
{
$this->load->model('ticket_model');
$ticket_id = mysql_real_escape_string($this->uri->segment(3));
if($_POST)
{
//save ticket
unset ($_POST['id']);
$_POST['id'] = $ticket_id;
$this->ticket_model->close_ticket($_POST);
redirect(base_url().'ticket/edit/'.$ticket_id.'/');
return;
}
redirect(base_url().'ticket/edit/'.$ticket_id.'/');
}
which it does. This controller is to post the information to the model to update the SQL.....
public function close_ticket($ticket_post)
{
$query = $this->db->query("SELECT id FROM ".$this->tables_ticket." WHERE id = '".mysql_real_escape_string($ticket_post['id'])."';");
if($query->num_rows() > 0)
{
$row = $query->row();
$query = $this->db->query("UPDATE ".$this->tables_ticket."
SET
status = '".mysql_real_escape_string($ticket_post['status'])."'
WHERE
id = '".mysql_real_escape_string($ticket_post['id'])."'
");
}
if($this->db->affected_rows() > 0) return true;
else return false;
}
then after all this, redirect back to the form. I am assuming that on redirect the form will then populate the drop list with the updated data. This is where I am struggling, as It sends the changed data, and somewhere it is not registering the change and returning the page, unchanged.
Question, would this work with a confirmation/secondary submission page, followed by redirect, and is it that I am trying to return the changed data in the same function where it is failing?
$body_data['ticket_list'] = $this->ticket_model->list_ticket();
$body_data['ticket_details'] = $this->ticket_model->get_ticket($ticket_id);
$body_data['ticket_summary'] = $this->ticket_model->list_ticket_summary($ticket_id);
$body_data['customer_list'] = $this->ticket_model->get_customer_details($ticket_id);
$body_data['precan_list'] = $this->ticket_model->list_messages();
$body_data['users_list'] = $this->ticket_model->list_users();
$foot_data['accordian_active'] = 5;
$this->load->view('head',$head_data);
$this->load->view('sidebar/service',$head_data);
$this->load->view('ticket/edit',$body_data);
$this->load->view('foot',$foot_data);
return;
The edit function simply returns a range of population query lists.
unless i need a new query to repopulate the ticket_details list?
I have the following PHP form, which posts back to a mysql database. My problem is that the update query seems to work, but is always overwritten with "checked". What I want to do is check is get the current value from the database, and then if there is a value in post, get that instead. Now...why is this not working? Do I need to have an else clause when checking if it is in _POST? If that's the case, do I even need to initilise the variable with $checkDeleted = "";?
<?php
error_reporting(E_ALL);
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
if (isset($_POST["cmd"]))
$cmd = $_POST["cmd"]; else die("Invalid URL");
if (isset($_GET["pk"])) {
$pk = $_GET["pk"];
}
$checkDeleted = "";
$con = mysqli_connect("localhost","user","pw", "db");
$getformdata = $con->query("select ARTICLE_NO, deleted from STATUS where ARTICLE_NO = '$pk'");
while ($row = mysqli_fetch_assoc($getformdata)) {
$ARTICLE_NO = $row['ARTICLE_NO'];
$checkDeleted = $row['deleted'];
}
$checkboxes = (isset($_POST['checkboxes'])? $_POST['checkboxes'] : array());
if (in_array('deleted', $checkboxes)) $checkDeleted = 'checked';
if($cmd=="submitinfo") {
if ($ARTICLE_NO == null) {
$statusQuery = "INSERT INTO STATUS VALUES (?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $pk, $checkDeleted);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
} else if ($ARTICLE_NO == $pk) {
$statusQuery = "UPDATE STATUS SET deleted = ? WHERE ARTICLE_NO = ?";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $checkDeleted, $pk);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
}
}
if($cmd=="EditStatusData") {
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"checkbox\" name=\"checkboxes[]\" value=\"deleted\" ".$checkDeleted." />
<label for=\"deleted\">Delete</label>
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
}
?>
I tried changing the line to set checkDeleted to the following, which made no difference..although it should?
if (in_array('deleted', $checkboxes)) {
$checkDeleted = 'checked';
} else {
$checkDeleted = '';
}
edit: OK, I have managed to get this to work, but only after changing to
$checkDeleted = in_array('deleted', $checkboxes) ? 'checked' : '';
as per the answer below, but this still did not work. For it to work I had to remove the database query, and replace it with one within the submitinfo branch, and one within the EditStatusData branch...why? Why is it not possible to have only one query?
if($cmd=="submitinfo") {
$getformdata = $con->query("select ARTICLE_NO from STATUS where ARTICLE_NO = '$pk'");
while ($row = mysqli_fetch_assoc($getformdata)) {
$ARTICLE_NO = $row['ARTICLE_NO'];
}
if ($ARTICLE_NO == null) { etc
and
if($cmd=="EditStatusData") {
$getformdata = $con->query("select deleted from STATUS where ARTICLE_NO = '$pk'");
while ($row = mysqli_fetch_assoc($getformdata)) {
$checkDeleted = $row['deleted'];
} etc
this is pretty much identical to your other question
mysql not updating from php form
there is nothing wrong with the code, it is working exactly as you want
What I want to do is get the current value from the database, and then if there is a value in post, get that instead.
case 1: html form with no tick
read from database $checkDeleted = 'checked'
if $_POST['checkboxes']['deleted'] is not set, leave $checkDeleted as is
writes 'checked' to database
case 2. html form with tick
read from database $checkDeleted = 'checked'
if $_POST['checkboxes']['deleted'] is set, change $checkDeleted = 'checked'
writes 'checked' to database
so no matter if you have a tick or not, once you have changed the database value to checked then, there is no way to change it
I will assume that what you want to do is always overwrite the database value with whatever the tick box is set to, in that case
replace this line
if (in_array('deleted', $checkboxes)) $checkDeleted = 'checked';
with this
$checkDeleted = in_array('deleted', $checkboxes) ? 'checked' : '';
This will only work if you're GET'ing data:
$getformdata = $con->query("select ARTICLE_NO, deleted from STATUS where ARTICLE_NO = '$pk'");
In your code $pk isn't set if your request is POST. You should also escape the $pk variable in this line as a user could put any data they liked in $_GET['pk'] and it could break your SQL query.