dont add rule for certain input field - php

So I have input fields and when they are submitted, I check to see if their inputted text appears in an array:
<form method="post">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'] {
$array = array('432423', '434', '3', '2', '213');
$success = true;
foreach ($_POST as $key=>$value) {
if (!empty($value) && $key != "submit") {
if (!in_array($value, $array)) {
$success = false;
}
}
}
var_dump($success);
// TRUE if all contains, FLASE if any one doesn't contain
}
?>
But if I wanted a certain input field not to have to be checked against the array, how would I do this

Then you probably want to check for another $key != something?
E.g.
if (!empty($value) && $key != "submit" && $key != "2") {
...
This would exclude the second input...

you can gather all the names in an array just set name="names[]" for the wanted inputs and you will be able to access all the inputs as an array ($_POST['names'])
<form method="post" action="">
<input type="text" name="names[]">
<input type="text" name="names[]">
<input type="text" name="names[]">
<input type="submit" name="submit">
</form>
and loop through them like this
if (! empty($_POST['names']) ) {
$names = $_POST['names'];
foreach ($names as $value) {
if (!empty($value)) {
if (!in_array($value, $array)) {
$success = false;
}
}
}
}

use https://jqueryvalidation.org
<form id="my_form" method="post">
<input type="text" name="a1">
<input type="text" name="a2">
<input type="text" name="a3">
<input type="checkbox" name="chk1" id="chk1">
<input type="submit" name="submit">
</form>
<script type="text/javascript">
$("#my_form").validate({
rules: {
"a1": {
required: true
},
"a2": {
required: true
},
"a3": {
required: true
},
"chk1": {
required: {
depends: function() {
return !$("#chk1").is(":checked");
}
}
}
}
});
</script>

Related

php input form can only be numbers not words

i made a form where you can put a number and show which one is the highest.
i want to make sure you can put any words in this form.
that there show a notification you cant put words in the form
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="text" name="tweedegetal" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
The following code shows a notification when a letter is typed.
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" id="eerstegetal" name="eerstegetal" oninput="Eerste_check()" placeholder="Eerste getal"><br>
<input type="text" id="tweedegetal" name="tweedegetal" oninput="Tweede_check()" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script>
function Eerste_check(){
var eerstegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(eerstegetal)){
alert('Eerstegetal should contain only numbers.')
}
}
function Tweede_check(){
var tweedegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(tweedegetal)){
alert('Tweedegetal should contain only numbers.')
}
}
</script>
Try the following:
<input type="number" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="number" name="tweedegetal" placeholder="Tweede getal"><br>
I hope it helps

Checkbox values are lost when form submitted with errors in PHP

I am using PHP and MYSQLI for my project. I have a form with which contains one text input field and three check boxes. When a user checks two boxes out of three and submits the form without filling the text input field I am showing an error.
Now what I want to achieve is that the particular check boxes that the user has checked should not get unchecked when error is displayed. Please understand that the category field will be same for all the check boxes in the form.
My form example is below:
<?php if(isset($_POST['submit'])) {
$full_name=$db->real_escape_string($_POST["full_name"]);
$checkbox = implode(',', $_POST["fruits"]);
if(empty($checkbox)) {
$errors = 'Please choose at least one fruit.';
}
if(!isset($errors)) {
// I am inserting the data
} else {
$errors;
}
}
?>
<form method="post" action="add.php">
<input type="text" name="full_name">
<input type="checkbox" name="fruits[]" value="Apple">
<input type="checkbox" name="fruits[]" value="Banana">
<input type="checkbox" name="fruits[]" value="Carrot">
<input type="submit" name="submit" value="Submit">
</form>
Do an in_array() check to see if the fruit is in the array, and then echo out checked="checked" to have it check the box (again).
<?php
if( isset($_POST['submit']) ) {
$errors = array();
$full_name = $db->real_escape_string($_POST["full_name"]);
//Initialize empty array (In case fruits isn't sent, if they didn't check any boxes)
$fruits = array();
//We get an array? Cool, set it to $fruits
if ( isset($_POST['fruits']) && is_array($_POST['fruits']) ) {
$fruits = $_POST['fruits'];
}
if ( empty($full_name) ) {
$errors[] = 'Please enter your name.';
}
if( empty($fruits) ) {
$errors[] = 'Please choose at least one fruit.';
}
if( empty($errors) )
{
//Change $fruits into a string
$fruits = implode(', ', $fruits);
// I am inserting the data
} else {
foreach ( $errors as $error )
{
echo '<p class="error">', $error, '</p>';
}
}
}
?>
<form method="post" action="add.php">
<input type="text" name="full_name" value="<?=htmlspecialchars($_POST['full_name'])?>" />
<input type="checkbox" name="fruits[]" value="Apple"<?=(in_array('Apple', $fruits) ? ' checked="checked"' : '') ?> />
<input type="checkbox" name="fruits[]" value="Banana"<?=(in_array('Banana', $fruits) ? ' checked="checked"' : '') ?> />
<input type="checkbox" name="fruits[]" value="Carrot"<?=(in_array('Carrot', $fruits) ? ' checked="checked"' : '') ?> />
<input type="submit" name="submit" value="Submit" />
</form>

Posting php results after calculation in form field

This form takes in data only in the "inp" field. To multiply two numbers you'd have to input the first number then hit "=" to send the number to the "out" field then type in the second number and hit "*". I am attempting to post the results($result) of calculations into the "out" field and not sure how to do this using php. Any help would be greatly appreciated.
php:
$input = $_POST['inp'];
$output= $_POST['out'];
if($_POST['submit'] == 'add') {
$result = $input + $output;
//set result to "out"
}
else if($_POST['submit'] == 'sub') {
$result = $input - $output;
//set result to "out"
}
else if($_POST['submit'] == 'mul') {
$result = $input * $output;
//set result to "out"
}
else if($_POST['submit'] == 'div') {
$result = $input / $output;
//set result to "out"
}
else if($_POST['submit'] == 'equ') {
$result = $input;
//set result to "out"
}
form:
<body>
<form action = "calc.php" method = "post">
<input type="text" value="0.0" name="out" readonly/>
<input type="text" value="0" name="inp"/>
<input type="submit" value="+" name="add"/>
<input type="submit" value="-" name="sub"/>
<input type="submit" value="*" name="mul"/>
<input type="submit" value="/" name="div"/>
<input type="submit" value="=" name="equ"/>
</form>
</body>
If you php and html code in the same file you can write simple write to out input value calculated result. Try something like this:
<body>
<form action = "calc.php" method = "post">
<input type="text"
value="<?=!empty($result)?$result:"0.0"?>" name="out" readonly/>
<input type="text" value="0" name="inp"/>
<input type="submit" value="+" name="add"/>
<input type="submit" value="-" name="sub"/>
<input type="submit" value="*" name="mul"/>
<input type="submit" value="/" name="div"/>
<input type="submit" value="=" name="equ"/>
</form>
</body>
I modified your code.
$result= '';
if ($_POST) {
$input = (int) $_POST['inp'];
$output= (int) $_POST['out'];
if(isset($_POST['add']) && !empty($input)) {
$result = $output + $input;
//set result to "out"
}
else if(isset($_POST['sub']) && !empty($input)) {
$result = $output - $input;
//set result to "out"
}
else if(isset($_POST['mul']) && !empty($input)) {
$result = $output * $input;
//set result to "out"
}
else if(isset($_POST['div']) && !empty($input)) {
$result = $output / $input;
//set result to "out"
}
else if(isset($_POST['equ']) && !empty($input)) {
$result = $input;
//set result to "out"
} else {
$error = "Please enter a number";
}
}
<body>
<form action="cal.php" method = "post">
<input type="text" value="<?=!empty($result)?$result:"0.0"?>" name="out" readonly/>
<input type="text" value="0" name="inp"/>
<input type="submit" value="+" name="add"/>
<input type="submit" value="-" name="sub"/>
<input type="submit" value="*" name="mul"/>
<input type="submit" value="/" name="div"/>
<input type="submit" value="=" name="equ"/>
</form>
<p><?=isset($error)?$error:''?></p>

What is the best way to supply many arguments to an if statement?

I have created a form with several user inputs but have the tedious task of checking whether each individual input is not empty before submission. Is there a quicker way, (such as using arrays perhaps) of listing all arguments to the if statement?
At the moment my code looks like this but if possible I would like it to be more efficient in future, like if I were to add more inputs.
<form action="sign-up.php" method="post" autocomplete="off" >
Name:<input type="text" name="name" />
Username:<<input type="text" name="username" /><br />
Password:<input type="password" name="password1" /><br />
Re-type Password:<input type="password" name="password2" /><br />
Email:<input type="text" name="email" />
Address:<input type="text" name="address" />
Post Code:<input type="text" name="postcode" />
City:<input type="text" name="city" />
<input class="submit" type="submit" value="sign up" />
</form>
<?php
if (!empty($_POST['name'])
&& !empty($_POST['username'])
&& !empty($_POST['password1'])
&& !empty($_POST['password2'])
&& !empty($_POST['email'])
&& !empty($_POST['address'])
&& !empty($_POST['postcode'])
&& !empty($_POST['city']) )
{
echo "information has been submitted";
}
else {
echo "please fill in all fields!"
}
?>
If you have any suggestions please comment.
So what this will do is loop through the $_POST values and check if they're empty. If one is found to be empty, it will set $hasErrorOccurred to true. The if statement below will determine if the input check is successful or not.
$hasErrorOccurred = false;
foreach ($_POST as $key => $value) {
if (empty($_POST[$key])) {
$hasErrorOccurred = true;
break;
}
}
if ($hasErrorOccurred) {
// Your error code here.
} else {
// Your successful code here.
}
Reading material:
break;
If you want to assign variables to each field input, this is how I did it.
foreach ($_POST as $key => $value) {
$$key = $_POST[$key]; //assigns input name to variable with the same name.
}
if(!empty($$key)) {
//code if all fields are not empty
}
else {
echo "Please fill in all fields";
}
Here is the way I tried to describe on comments to Script47's answer so I can clarify my point a little bit better:
$requiredFields = ['name','username','password1','password2'];
foreach ($requiredFields as $field) {
if (!array_key_exists($field, $_POST) || empty($_POST[$field])) {
displayMissingFieldAlert($field);
}
}
// do the submit etc.
...
This way you can catch if a field is somehow forgotten, misspelled or left out of the submission.

Form Only Posting In 1 Column

Can someone explain or show me why my form is only posting in 1 column when it should be posting in 2 columns for example.
Here is my form
<form action="{$baseurl}/redirect" method="post" enctype="multipart/form-data" id="details_change">
<textarea name="about_me" cols="53" rows="5" class="submit_form_textfield">{$profile_user.about_me}</textarea>
<input type="text" name="profile_message" />
<input type="hidden" name="action" value="user_details" />
<input type="submit" class="submit_form_button" value="Update Details" id="details_change">
</form>
And here is my PHP
if (isset($action) && $action=='user_details' && isset($_SESSION['loggeduser_id'])) {
$user = new User();
if (isset($_POST['about_me']) && isset($_POST['about_me'])) {
$_POST['$about_me'] = preg_replace("/[^a-z]/i","",$_POST['about_me']);
} else {
$about_me = '';
}
if (isset($_POST['profile_message']) && isset($_POST['profile_message'])) {
$_POST['$profile_message'] = preg_replace("/[^a-z]/i","",$_POST['profile_message']);
} else {
$profile_message = '';
}
$user->update($_SESSION['loggeduser_id'],array("about_me" => $about_me,"profile_message" => $profile_message));
}
And I have columns in my user table called about_me and profile_message
And what happens is it will only post about_me and not profile_message any reason why?
You need to use $_POST['user_details'] and $_POST['profile_message']
In HTML:
<form action="{$baseurl}/redirect" method="post" enctype="multipart/form-data" id="details_change">
<textarea name="about_me" cols="53" rows="5" class="submit_form_textfield">{$profile_user.about_me}</textarea>
<input type="text" name="profile_message" />
<input type="hidden" name="user_details" value="" />
<input type="submit" class="submit_form_button" value="Update Details" name="action" >
</form>
PHP:
if (isset($_POST['action']) && isset($_SESSION['loggeduser_id'])) {
$user = new User();
if (isset($_POST['profile_message'])) {
$profile_message = preg_replace("/[^a-z]/i","",$_POST['profile_message']);
} else {
$profile_message = '';
}
if (isset($_POST['user_details']) && isset($_POST['user_details'])) {
$user_details = preg_replace("/[^a-z]/i","",$_POST['user_details']);
} else {
$user_details = '';
}
$about_me = $_POST['about_me'];
$user->update($_SESSION['loggeduser_id'],array("about_me" => $about_me,"profile_message" => $profile_message));
}

Categories