Button form submission not submitting NULL - php

I am working with a fairly straight forward form yet for some reason it is not submitting NULL results and instead submits them as empty results.
<div class="span6">
<form action="" method="POST">
<div class="block-fluid without-head">
<div class="toolbar clearfix">
<div class="right">
<div class="btn-group">
<button type="submit" class="btn btn-small btn-warning tip" data-original-title="Submit Aritcle">
<span class="icon-ok icon-white"></span>
</button>
<button type="button" class="btn btn-small btn-danger tip" data-original-title="Delete Article">
<span class="icon-remove icon-white"></span>
</button>
</div>
</div>
<div class="left">
<div style="font-size: 11pt; font-family: -webkit-body; font-weight: bolder;">Article Exchange Request</div>
</div>
</div>
<div class="row-form clearfix">
<div class="span3">Title</div>
<div class="span9"><input type="text" name="title" value="" placeholder="main subject title"></div>
</div>
<div class="row-form clearfix">
<div class="span3">First Sentence</div>
<div class="span9"><input type="text" name="s1" value="" placeholder="Sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Second Sentence</div>
<div class="span9"><input type="text" name="s2" value="" placeholder="Optional sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Third Sentence</div>
<div class="span9"><input type="text" name="s3" value="" placeholder="Optional Sentence with max of 200 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Website Url</div>
<div class="span9"><input type="text" name="link" value="" placeholder="Url to be included in articles"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Website Url Title</div>
<div class="span9"><input type="text" name="link_text" value="" placeholder="Url text to be included in articles limit 150 characters"></div>
</div>
<div class="row-form clearfix">
<div class="span3">Credit Offer</div>
<div class="span9"><input type="text" name="cost_value" value="" placeholder="Example: 100"></div>
</div>
</div>
</form>
</div>
The problem is someone can just come along and submit the form without entering any data at all, and it still submits, and adds empty results to every column in the database. Meaning no NULL values are being set in the database.
My form processing
<?
if (isset($_POST[cost_value])) {
$stmt = $db->prepare("SELECT credits from member_credits WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$row = $stmt->fetch();
$count = $row[credits];
if ($count > $_POST[cost_value]) {
$stmt = $db->prepare('INSERT INTO article_requests (title, s1, s2, s3, link, link_text, offer, username) VALUES (:title, :s1, :s2, :s3, :link, :link_text, :offer, :username)');
$stmt->bindValue(':title', $_POST[title]);
$stmt->bindValue(':s1', $_POST[s1]);
$stmt->bindValue(':s2', $_POST[s2]);
$stmt->bindValue(':s3', $_POST[s3]);
$stmt->bindValue(':link', $_POST[link]);
$stmt->bindValue(':link_text', $_POST[link_text]);
$stmt->bindValue(':offer', $_POST[cost_value]);
$stmt->bindValue(':username', $username);
$stmt->execute();
}
}
?>
What I expect to happen on submission is if no value is entered in the form it should be set to NULL... that would mean if no $_POST[cost_value] was set, the form wouldn't submit. As it stands now, it is ALWAYS seeing $_POST[cost_value] as being set - sometimes to a value such as $_POST[cost_value] = '100'; and other times $_POST[cost_value] = ''; but in both cases, the form will submit. Equally I have the database set so that only the values of s2 and s3 should be able to be null, however when everything is submitting empty instead of null, thats mostly useless.
What exactly am I missing? Why will it not say $_POST[cost_value] = NULL; if the user has not input a value? Why is it submitting ''?? I have a feeling its going to be something basic I am overlooking, I just don't see it....
UPDATE FOR CLARITY
I know there are a number of ways to fix this. I can use if then tests, I can use temporary variables, I can check for the value itself is something other than ''. I know WHAT the work arounds are. I don't understand WHY they are needed. Why is it I make forms every day of the week using if isset, and everyday that works. If a form has no values input from the user, the form won't submit because an if isset returns false. So why is it on this particular form it is submitting '' instead of saying !isset don't process.

// Assign a var to the post.
$DIRTY_Var = $_POST['varinputname'];
// ensure the var is cleaned (no funny business when submitting)
$CLEAN_Var = filter_var($DIRTY_Var,` FILTER_SANITIZE_STRING);
// check if the var is empty, or has value. If empty it will set the var to null;
if (!$CLEAN_Var) { return $CLEAN_Var = null; }
// validate input
$valid = true;
// insert data
if ($valid) {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO Table ("
."ColumnNames"
.")"
."VALUES("
."?"
.")";
$q = $pdo->prepare($sql);
$q->execute(array($CLEAN_Var));
// Once INSERT is completed, we will redirect.
header("Location:" 'link.php'); exit;
}

Try
If(isset($_POST['cost_value']) && !empty($_POST['cost_value']){
// your code
}

Related

Display inline arrays

var html3 = '<div class="row" id="parent-autor"> <p id="auth-del"><i class="fa fa-minus-square" aria-hidden="true"></i></p> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="altautorprenume[]" placeholder="Prename"> </div> </div> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="altautornume[]" placeholder="Name"> </div> </div><div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" name="institutie[]" id="institutie" placeholder="Institutions"> </div> </div></div>';
$("#add_aut").click(function(e){
$('#auth-rows').append(html3);
});
$('#auth-rows').on('click', '#auth-del', function(E){
$(this).parent('div').remove();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="add-plus"></div>
<div class="col-md-12">
<h5>Add more persons </h5>
<span class="btn btn-primary" id="add_aut" style="">Click here to add</span>
</div>
</div>
<div id="auth-rows"></div>
i have an formular which user can add more clients to invite at party when user click on Add a new row with 3 fields appear he can add how many he want,
these values dynamically i want to show on email, for example:
User fill all fields and add 3 more users where they have Name PreName Instituional,look what i did:
$personName= $_POST['personname'];
$personPrename= $_POST['personprename'];
$institution= $_POST['institution'];
$otherPersonName=" ";
$otherPersonPreName="";
$otherPersonInstitution= "";
foreach($personName as $product) {
$otherPersonPreName.= "$product";
}
foreach($personPrename as $products) {
$altiautoriNume .= "$products";
}
foreach($institution as $productss) {
$otherPersonInstitution.= "$productss";
}
EXAMPLE:
And in email content i want to display like this:
<hr>
John(first name of person added) Doe(first Prename of person added) Microsoft(first Institution of person added)
<hr>
Mike(second name of person added) Stuart(second Prename of person added) Facebook(second Institution of person added)
<hr>
I know i did something wrong.
I put even html to see truly what i want to do, i want to group Name Prename Institution per line
You can use array-map with null as first parameter to group the array and then use implode to concat the strings.
Consider the following:
$arr = array_map(null, $personName, $personPrename, $institution);
foreach($arr as $e)
echo implode(" ", $e) . PHP_EOL;
Live example: 3v4l

How to have show error and not allow two inputs to be submitted in form PHP

One my form I have the option to choose from a select box, or to manually enter the information.
I want to prevent user from entering both. They should either choose from the select OR enter manually if their selection is not already there.
html code
<div class="row">
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-3">
<label for="selectComplvl" class="regions" >Region</label></div>
<div class="col-sm-8">
<select class="form-control regionbox" id="region" value="" name="region">
<option>---Select---</option>
<?php
$region_sql = "SELECT * FROM `regions`";
$region_res = mysqli_query($con, $region_sql);
if(mysqli_num_rows($region_res) > 0){
while($region_row = mysqli_fetch_array($region_res)){
echo "<option value='".$region_row[id]."'>".$region_row[region]."</option>";
}
}
?>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-4">
<label for="feisEntered" class="feis">Feis Entered</label></div>
<div class="col-sm-8">
<select class="form-control feisbox" id="feisEntered" name="feisEntered">
<option>First choose a Region</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group col-sm-4">
<div class="row">
<div class="col-sm-3">
<label for="feisEntered" class="enterfeis">Or Enter</label></div>
<div class="col-sm-8">
<input id="inputfeis" type="text" name="feisEntered" class="form-control" placeholder="Feis name - MM/DD/YYYY">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
And my query:
if(isset($_POST['submit'])){
$dancer=$_POST['dancer'];
$dancer = mysqli_real_escape_string($con,$dancer);
$level=$_POST['level'];
$level = mysqli_real_escape_string($con,$level);
$feisEntered=$_POST['feisEntered'];
$feisEntered = mysqli_real_escape_string($con,$feisEntered);
$danceName=$_POST['danceName'];
$danceName = mysqli_real_escape_string($con,$danceName);
$compNum=$_POST['compNum'];
$compNum = mysqli_real_escape_string($con,$compNum);
$competitor = $_POST['competitor'];
$competitor = mysqli_real_escape_string($con,$competitor);
$danceScore = $_POST['danceScore'];
$danceScore = mysqli_real_escape_string($con,$danceScore);
$placement = $_POST['placement'];
$placement = mysqli_real_escape_string($con,$placement);
$firstScore = $_POST['firstScore'];
$firstScore = mysqli_real_escape_string($con,$firstScore);
$secondScore = $_POST['secondScore'];
$secondScore = mysqli_real_escape_string($con,$secondScore);
$thirdScore = $_POST['thirdScore'];
$thirdScore = mysqli_real_escape_string($con,$thirdScore);
$judge = $_POST['judge'];
$judge = mysqli_real_escape_string($con,$judge);
$comments = $_POST['comments'];
$comments = mysqli_real_escape_string($con,$comments);
$query = "INSERT INTO reports (user_id, dancer_id1, dancer_name, competition_level1, feis_entered, dance_name1, competition_number1, number_competitors1, dancer_score1, dancer_placement1, firstpl_score1, 2ndpl_score1, 3rdpl_score1, judge_name1, judge_comment1) VALUES ('$id','$dancerID', '$dancer', '$level', '$feisEntered', '$danceName', '$compNum', '$competitor', '$danceScore', '$placement', '$firstScore', '$secondScore', '$thirdScore', '$judge', '$comments')";
$result = mysqli_query($con, $query);
}
So what I want to happen is a error message appears if they fill out both saying "Please choose only one". That way only one enters into database.
Never rely on just JS to validate input. Use JS to implement the behavior you speak of and then handle all possible outcomes in PHP. If someone is fiddling with your JS and bypasses the behavior you implement, you need to be able to handle that in your PHP code as well to make sure DB doesnt get unexpected input and break everything. Just like Justin said above, you could select one or the other, or throw an error. I recommend throwing an error and telling the user to make sure they have JS enabled.
In your HTML document, you should use Javascript to validate the user input before submitting the form to the PHP script. Then, in the PHP script, you should double-check that values were not received for both the select and the input (this could happen if the user does not have Javascript enabled, or they somehow bypass the validation) and determine what you want to do in that case (select one over the other, or exit with an error).

Insert query not inserting in database

So I'm trying to insert some text into a already existing table. If I insert the text into the text field and press submit, I'll get a var_dump on a other page that shows the information that I want to insert but it doesnt send it to the database or something. I hope you can help me with what I'm doing wrong.
This is my insert query
public function insertComment($commentaar, $idBestelling){
try{
$stmt = $this->_db->prepare('UPDATE `apotheek`.`Bestelling` SET `commentaar` = :commentaar WHERE `Bestelling`.`idBestelling` = :idBestelling;');
if($stmt->execute(array(
':commentaar' => $commentaar,
':idBestelling' => $idBestelling))){
return true;
} else {
return false;
}
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
And here you can find the code from the webpage.
<div class="row">
<form role="form" method="post" action="/?content=bezorgen">
<div class="col-xs-12 col-sm-12 col-md-12 loginborder">
<h2 class="loginhead">Bestelling no. <?php print($data['idBestelling']); ?> <?php ($data['isSpoed'] == '0') ? print('') : print('deze bestelling is met SPOED') ?></h2>
<hr>
<div class="row col-6 col-md-6 col-sm-12 col-xs-12">
<div class="loginhead">
<h3>Commentaar</h3>
<hr>
</div>
<div>
<textarea rows="9" cols="74" name="commentaar"><?php print($data['commentaar']); ?></textarea>
</div>
</div>
<div class="row registerbtn">
<div class="col-xs-12 col-md-12" style="text-align:right;"><input type="submit" name="submit" value="Verstuur" class="btn btn-lg" tabindex="5"></div>
</div>
</div>
</form>
And the php
$data = $user->getBestellingPatient($_POST['idBestelling']);
if(isset($_POST['submit'])){
$user->insertComment($_POST['commentaar'], $_POST['idBestelling']);
};
I think you are trying to update a comment which is already exist in the database.
You should add a hidden field in the form to hold the id of the the post (Mostly auto incremented id from DB)
Add the below element below your textarea element
<input type='hidden' name='idBestelling'<?php print($data['idBestelling']); ?>/>
So when you are updating id will be passed as a part of the form then you can receive it usinig $_POST
you should try this:
$stmt = $this->_db->query('UPDATE `apotheek`.`Bestelling` SET `commentaar` = :commentaar WHERE `Bestelling`.`idBestelling` = :idBestelling;');

Can you assign values to hidden fields in a form, through a php function, to be stored in a database?

I created a form you know; text fields, radio buttons and the submit button
within the said form, I have a div enclosing a section of the radio buttons hidden and a text field upon page load using inline CSS display:none;
If the end user chose yes, the hidden fields will be displayed using a jquery function. If the user chose No or Not Sure, the form will remain hidden or become hidden using the same jquery function.
If the user chose No or Not Sure, i want to automatically assign values for the hidden fields and store them in database.
Here is my form:
<div id = "relation" style = "display: none;">
<p class= "form-p" >Who are you related o?</p>
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-4">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Bride" required />Bride
</label>
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Groom" required />Groom
</label>
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Friend" required />Friend
</label>
<span class="error"><?php echo $famErr;?></span>
</div>
</div>
</div>
<p class = "form-p">Guests in your party, including yourself: </p>
<div class = "form-group">
<label class="control-label col-sm-4"></label>
<div class="col-xs-2">
<input type = "text" class = "form-control" name="num" placeholder = "0" required />
<span class="error"><?php echo $numErr;?></span>
</div>
</div>
</div> <!-- end of id relation-->
Here are the functions:
// function to add RSVP user entry to the database
public function user_attending_storage_RSVP($name, $email, $attend, $fam, $num){
$replies = "INSERT INTO rsvp (name, attending, family, total) VALUES (:name,:attending,:family,:total)";
try{
$query = $this->conn->prepare($replies);
$results = $query->execute(array(":name"=>$name, ":attending"=>$attend, ":family"=>$fam, ":total"=>$num));
}
catch(PDOException $e){
die($e->getMessage());
}
}
// function to add RSVP user entry to the database
public function user_not_attending_storage_RSVP($name, $email, $attend){
$replies = "INSERT INTO rsvp (name, attending, family, total) VALUES (:name,:attending,:family,:total)";
try{
$query = $this->conn->prepare($replies);
$results = $query->execute(array(":name"=>$name, ":attending"=>$attend, ":family"=>$fam, ":total"=>$num));
}
catch(PDOException $e){
die($e->getMessage());
}
}
Here's how I call the function on the webpage
// check for data in fields
if(isset($_POST['name']) ==true && isset($_POST['email']) ==true && isset($_POST['attending']) && isset($_POST['family']) && isset($_POST['num'])){
$name=test_input($_POST['name']);
$email=test_input($_POST['email']);
$attend=test_input($_POST['attending']);
$fam=test_input($_POST['family']);
$num=test_input($_POST['num']);
if($attend == "No" || $attend == "Not Sure"){
$fam = "nothing";
$num = 0;
//inserting user data from form into database
$genQuery->user_Not_attending_storage_RSVP($name, $email, $attend);
}
else{
//inserting user data from form into database
$genQuery->user_attending_storage_RSVP($name, $email, $attend, $fam, $num);
}
// send mail to user
$genQuery->user_invite_confirmation_RSVP($name, $email, $attend,$fam, $num);
}
You can use the getElementById() method...
if(getElementById('input_id').value() == 'no' || getElementById('user_id').value() == 'not sure'){getElementById('input_you_want_to_change).value('Defualt value')}
This will change the value if the user selects no or not sure. Then use PHP to store this new value in the database.

How to add an PHP IF statement in this Script?

$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
I want to be able to add an if statement in this result_2 string.
This is for displaying a product, and i would like to display price depending on users session value?
eg.
if ($_SESSION['customer_x'] == a) {
display price a
}
else if ($_SESSION['customer_x'] == b) {
display price b
}
Is this the correct method to be able to add an if statement to a JSON query?
After Starting your while loop, put a if else there,
$price ="";
if ($__SESSION['customer_x'] == a) {
$price='display price a';
}
else if ($_SESSION['customer_x'] == b) {
$price='display price b';
}
and now echo this price where ever you want to in your html
this is more neet and less messy way
You can use a ternary if operator to have conditional statements inside strings, example
$bool = false;
echo "The value of \$bool is " . ($bool == true ? "TRUE" : "FALSE");
Example in use
To add that you can keep doing the same but:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ // the next of the content
$priceOfSession = ($__SESSION['customer_x'] == a) ? 'pricea' : 'priceb';
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
'.$priceOfSession.'
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
</div>
';
}
So if you want to evaluate only two conditions if otherwise the if you want, simply add it there. Do as you add the $ row but before defining value.

Categories