Radio Button not storing the value in database? - php

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)

Related

Dropdown to read in and sort users with PHP

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.

Insert Foreign Key value from PHP using SELECT option

I creating an inventory web-base system by using php and php myadmin (InnoDB). I want to insert the value in inventory when I inserting the record, I can see the data of the (FK) in the dropdown but when I submit the form the data to the db, it returns as no input value in the field and the dropdown not there anymore. Is the way I'm using the foreign key in the dropdown wrong?
I have a table that contains multiple foreign keys.
Table Inventory(
id (pk),
name,
condition_(fk),
producttype (fk))
Table condition_type(
condition_ (pk))
Table producttype(
producttype(fk))
<?php
// Include config file
require_once "../config.php";
// Define variables and initialize with empty values
$name = $condition_ = $producttype = "";
$name_err = $condition_err = $producttype_err = "";
$sql2 = "SELECT * FROM condition_type";
$sql4 = "SELECT * FROM producttype";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
}else{
$name = $input_name;
}
// Validate condition
$input_condition = trim($_POST["condition_"]);
if(empty($input_condition)){
$condition_err = "Please choose the condition.";
} else{
$condition_ = $input_condition;
}
// Validate producttype
$input_producttype = trim($_POST["prodcuttype"]);
if(empty($input_producttype)){
$producttype_err = "Please enter the product type..";
} else{
$producttype = $input_producttype;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($condition_err) && empty($producttype_err)){
// Prepare an insert statement
$sql = "INSERT INTO inventory (name, condition_, producttype) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_name, $param_condition, $param_producttype);
// Set parameters
$param_name = $name;
$param_condition = $condition;
$param_producttype = $producttype;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: ../application");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
-------> This is the form
<div class="form-group <?php echo (!empty($condition_err)) ? 'has-error'
: ''; ?>">
<label>Condition</label>
</br>
<select id="condition_" name="condition_" class="form-control" value="<?
php echo $condition_ ;?>">
<option>Please Select Product Condition</option>
<?php
if($result2 = $mysqli ->query($sql2)){
while($row = $result2->fetch_array()){
echo "<option value=".$row['condition_'].">" .$row['condition_']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $condition_err;?></span>
</div>
<div class="form-group <?php echo (!empty($producttype_err)) ? 'has-
error' : ''; ?>">
<label>Product</label>
</br>
<select name="producttype" class="form-control" value="<?php echo
$producttype ;?>">
<?php if($result4 = $mysqli ->query($sql4)){
while($row = $result4->fetch_array()){
echo "<option value=".$row['producttype'].">" .$row['producttype']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $manufacturer_err;?></span>
</div>
So when I submit it return as the condition and producttype are empty. I think the error is because of
}
// Close connection
$mysqli->close();
}
statement that already close. But I don't know to place it.
PHP Warning: mysqli::query(): Couldn't fetch mysqli in /home/my-path/application/create_new.php on line 173
You should debug the html form first by right click with 'Inspect element' and make sure that the 'Select' value is getting?

PHP - Check <option> value is equal to <input> value

I'm writing a website that allows for people to add movies into a database.
At the moment the user can either select from a director that is already within the database or create a new one.
<div class='dropdownrow' id='director_namerow'>
<div>
<label for='director_name'>Director:</label>
<select name='director_name'>
<option value='blank' selected>Select...</option>
<?php
$sql = "SELECT *
FROM director
ORDER BY director_name ASC";
$director = mysql_query($sql);
while ($directors=mysql_fetch_array($director)) {
?>
<option value="<?php echo $directors['director_id']; ?>"><?php echo $directors['director_name']; ?></option>
<?php
}
?>
</select>
<span style = 'color:red;'> *</span>
</div>
<div>
<label for='director_namenew'>Or new director:</label>
<input type='text' name='director_namenew' size='25' maxlength='128' />
</div>
</div>
So the problem is, how do I check that "director_namenew" isn't equal to "director_name" AND that director_namenew isn't already within the database.
Furthermore, is the "director_namenew" isn't within the database, I need to add them into the database too.
Controller Script
function validateDirector ($formdata) {
if(($formdata['director_name'] == "blank") && ($formdata['director_namenew'] == "")){
return false;
}
else if($formdata['hidden_director_name'] == $formdata['director_namenew']){
echo 'cannot have directors match';
return false;
}
else {
return true;
}
} // TO COMPLETE
Thanks guys,
pb.
Answer to my own question
if(($formdata['director_name'] == "blank") && ($formdata['director_namenew'] == "")){
print "<p>Please enter in director information - Use the back button on your browser to rectify this problem.</p>";
return false;
}
else if($formdata['director_namenew']) {
$doesntExist = true;
$db = getDBConnection();
$directors = $db->query("SELECT director_name FROM director");
//Check each one
foreach ($directors as $director){
//If the username is already in the DB stop looking
if($formdata['director_namenew'] == $director['director_name']){
$doesntExist = false;
print "<p>Director entered in new director already exists, please enter in new director or select from drop down menu - Use the back button on your browser to rectify this problem.</p>";
break;
}
}
//DB connection closed when PDO object isn't referenced
//ie setting $db to null closes the connection
$db = null;
return $doesntExist;
}
-- However, how would I check to see if both the drop down and input field have been filled?
I was thinking something like:
else if(($formdata['director_name']) && ($formdata['director_namenew'])) {
print "Please select either new director or director from drop down menu";
}
And checking on the submit to see if both $_POST variables have been submitted.
What do you think?
You can use Ajax to transfer the front-end requirement to back-end so that seperate the view and controller.
view.html (Some modification base on your original code):
<script src="checkRepeatName.js"></script>
<div>
<label for='director_namenew'>Or new director:</label>
<input type='text' name='director_namenew' size='25' maxlength='128' />
<span id="notation"></span>
</div>
checkRepeatName.js (Written with jQuery):
$("input[name='director_namenew']").change(function(){
$.get("backend.php?dnamenew=" + this.value,function(data,status){
$(".notation").text(data);
});
});
backend.php (I use Object Oriented Style of PHP code,and refer the recommendation of #Barmar):
<?php
if (isset($_GET['dnamenew'])) {
$director_namenew = $_GET['dnamenew'];
};
$dbconn = new mysqli(HOST, USERNAME, PASSWORD, DBNAME, PORT);
$sqlStat = sprintf('SELECT director_id FROM director WHERE director_name = "%s";', $director_namenew);
if ($sqlQuery = $dbconn->query($sqlStat)){
if ($sqlQuery->num_rows == 0){
echo 'This is validated database name';
} else {
echo 'Invalidated database name!';
}
}
$dbconn->close;
?>
-------- supplement something --------
It maybe something help in design dynamic dropdown menu with MVC design pattern
view.html:
<div class='dropdownrow' id='director_namerow'>
<div>
<label for='director_name'>Director:</label>
<select name='director_name'>
<option value='blank' selected>Select...</option>
</select>
<span style = 'color:red;'> *</span>
</div>
<div>
controllor.js:
$("select[name='director_name']").change(function(){
$.get("optionOutput.php", function(data,status){
$("select[name='director_name']").append(data); // append the call-back message from back-end file
});
});
optionOutput.php:
<?php
include 'dbmng/dbconfig.php';
$dbconn = new mysqli(HOST, USERNAME, PASSWORD, DBNAME, PORT);
$sqlStat = 'SELECT * FROM director ORDER BY director_name ASC;';
if ($sqlQue = $dbconn->query($sqlStat)){
while($sqlRes = $sqlQue->fetch_assoc()){
$output = sprintf('<option value = "%d">%s</option>', $sqlResult['director_id'], $sqlRes['director_name']);
echo $output;
}
}
$dbconn->close;
?>

Issue with checkbox value in database...?

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.

PHP Comparing variables returns false every time

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.
}

Categories