How to check strlen of multiple input fields with short code - php

Multiple input fields like
<input type="text" name="row1[]" id="date1">
<input type="text" name="row1[]" id="amount1">
<input type="text" name="row1[]" id="name1">
<input type="text" name="row1[]" id="document1">
Want to check if number of characters in certain fields (not all fields) is at least 1 (in the example do not want to check number of characters in id="document1". Now using this code
if ( (strlen($_POST['row1'][0]) >= 1) or (strlen($_POST['row1'][1]) >= 1) or (strlen($_POST['row1'][2]) >= 1)) ) {
}
Is it possible to shorten code to something like (this is not working code)?
if ( (strlen($_POST['row1']??want_to_check??) >= 1) ) {
}
And input something like (also not working and not real)
<input type="text" name="row1[]??want_to_check??" id="date1">
<input type="text" name="row1[]??want_to_check??" id="amount1">
<input type="text" name="row1[]??want_to_check??" id="name1">
<input type="text" name="row1[]??do_not_want_to_check??" id="document1">
Check number of characters only in certain fields (not all fields)

a tricky shorthand
if (count(array_filter($_POST['row1'],'trim')) != count($_POST['row1'])) {
//not all fields are set
}
but in general, if you see a repetition - you can be sure that a loop can be used. Look:
if ( (
strlen($_POST['row1'][0]) >= 1)
or (strlen($_POST['row1'][1]) >= 1)
or (strlen($_POST['row1'][2]) >= 1)) )
three repeated operators with only counter changing. I am sure you can write a loop for this. Can't you?
Update
Make sensible field names
<input type="text" name="row1[date]" id="date1">
<input type="text" name="row1[amount]" id="amount1">
<input type="text" name="row1[name]" id="name1">
<input type="text" name="row1[document]" id="document1">
Create an array with required field names
$req = array('date1','amount1','name1');
Check your input against this array in a loop

Something like this might work
function checkLength($inputs) {
foreach($inputs as $input) {
if(strlen($input) < 1) return false;
}
return true;
}
if(checkLength(array($_POST['input1'], $_POST['input2'], $_POST['input3']))) {
}

You can loop through fields using foreach
$field_set = false;
if(!empty($_POST['row1'])){
foreach($_POST['row1'] as $key => $row){
//Your code here
if(trim($_POST['row1']))
$field_set = true;
}
}
This will work if you have dynamic number of fields.

Related

Confused by how !empty() works in my if-condition

I'm confused by what counts as empty in this code logic. I have a variable amount of table rows (additional rows are dynamically inserted via ajax) that each accept four inputs. The logic I want is for a particular row - whose inputs are incomplete - to be unable to update a database:
if ((isset($_POST['_branch']) && !empty($_POST['_branch']))
&& (isset($_POST['_day']) && !empty($_POST['_day']))
&& (isset($_POST['_starttimepicker']) && !empty($_POST['_starttimepicker']))
&& (isset($_POST['_endtimepicker']) && !empty($_POST['_endtimepicker']))) {
$b_id = $_POST['_branch'];
$w_date = $_POST['_day'];
$s_time = $_POST['_starttimepicker'];
$e_time = $_POST['_endtimepicker'];
// ... rest of code comes here
}
The code snippet where the four inputs are handled:
<td>
<input class="form-control" type="text" id="_starttimepicker" name="_starttimepicker[]" placeholder="Enter Time" />
</td>
<td>
<input class="form-control" type="text" id="_endtimepicker" name="_endtimepicker[]" placeholder="Enter Time" />
</td>
When I have start time and end time "empty" (haven't interacted with them; the placeholder remains as "Enter Time"), the if-condition logic above still processes and the database is ultimately updated (with bad values). Even when I try to play around with the default value parameter (I have value = "" and "red"):
<td>
<input class="form-control" type="text" id="_starttimepicker" name="_starttimepicker[]" value="" placeholder="Enter Time" />
</td>
<td>
<input class="form-control" type="text" id="_endtimepicker" name="_endtimepicker[]" value="red" placeholder="Enter Time" />
</td>
The if logic still processes (also, the relevant database value where I had value="red" remains as "". I thought it would have taken the default value "red", so maybe I'm misunderstanding this).
What am I misunderstanding? Any advice?
I see that you use input arrays. To check empty form fields that are input arrays, you need more complicate than just empty().
Example HTML form:
<form method="post">
<input class="form-control" type="text" id="_starttimepicker" name="_starttimepicker[]" placeholder="Enter Time" />
<input class="form-control" type="text" id="_endtimepicker" name="_endtimepicker[]" placeholder="Enter Time" />
<button type="submit">Submit</button>
</form>
Here is PHP function to check it and how to use.
$_starttimepicker = ($_POST['_starttimepicker'] ?? []);
// in PHP older than 7.0 use (isset($_POST['_starttimepicker']) ? $_POST['_starttimepicker'] : []) instead.
$_endtimepicker = ($_POST['_endtimepicker'] ?? []);
/**
* Check if ANY fields are empty.
*
* #param array $fields The input form field, one by one.
* #return bool Return `true` if one of a form field is empty. Return `false` for otherwise.
*/
function isEmptyFields(...$fields)
{
$foundEmpty = false;
foreach ($fields as $field) {
if (is_array($field) && !empty($field)) {
foreach ($field as $index => $value) {
if (empty($value)) {
$foundEmpty = true;
break;
}
}
} else {
if (empty($field)) {
$foundEmpty = true;
break;
}
}
}
return $foundEmpty;
}
if (!isEmptyFields($_starttimepicker, $_endtimepicker)) {
// if all fields are NOT empty.
echo 'save your data.';
}
Tested submit the form by filled all fields, the result is in condition (save your data.) but if empty just one, it will not goes into if condition.

PHP arrays validation

I have a form that gets validated when submit. I make sure some fields are not empty, date fields have a valid format, etc. I have a block of check boxes with a text input next to it.
Option 1
<input type="checkbox" name="jobBonusId[]" value="1" />
Option 2
<input type="checkbox" name="jobBonusId[]" value="2" />
Option 3
<input type="checkbox" name="jobBonusId[]" value="3" />
Amount 1
<input type="number" name="jobBonusAmount[]" step="0.01" value="0.00" />
Amount 2
<input type="number" name="jobBonusAmount[]" step="0.01" value="0.00" />
Amount 3
<input type="number" name="jobBonusAmount[]" step="0.01" value="0.00" />
So, if any of the jobBonusId[] checkbox gets checked it creates an array. Now, I want to validate the jobBonusAmount[] if its -parent- checkbox was checked and make sure is not empty or equals 0.00.
So far, I have the following code:
// Run the script
if (isset($_POST['addJobRecord']) && $_POST['addJobRecord']=='oTzm50xfm') {
// Validate date format
if (!validateDate($jobDateStart) || !empty($jobDateEnd) && !validateDate($jobDateEnd)) {
// Show the form
$displayContent = $displayForm;
// Validate data dates
} else if ($jobTimeIn>$jobTimeOut) {
// Show the form
$displayContent = $displayForm;
// Validate bonus values
} else if (!empty($jobBonusId) && is_array($jobBonusId)) {
// At least one jobBonusId checkbox was checked
// Make sure its child input is not empty
... HERE'S WHERE I'M STUCK ...
} else {
// Everything looks good
// Add record to database
}
}
Any ideas how to accomplish it?
Thank you much!
You can use array key, and check child by jobBonusId key:
foreach ($jobBonusId as $key => $bonusId) {
if (!empty($bonusId)) {
if (!empty($jobBonusAmount[$key])) { // check a child
// if child is filled
} else {
// not filled
}
}
}
It means, that $jobBonusId array is the same to $jobBonusAmount array

Count filled input boxes

<input type="number" name="day1">
<input type="number" name="day2">
<input type="number" name="day3>
My question is, how to count only filled fields, so if I fill only day1 with some value, count result will be 1, and if I fill 3 days with some values, count result will be 3.
I'm using php + html.
It would be better to use an array of inputs instead of numbered names:
<input type="number" name="day[1]">
<input type="number" name="day[2]">
<input type="number" name="day[3]">
Then in PHP just filter out empty ones:
$count = count(array_filter($_POST['day']));
That will filter out 0 as well, if you don't want that then filter checking for an empty string:
$count = count(array_filter($_POST['day'], function($v) { return $v !== '';}));

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

Loop through 3 arrays at once and save values in the database

I have three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.
I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}

Categories