How to count the number of values entered in html input element? - php

I am working on html form present in a php file as shown below in which I want to count the entered html input values.
Php/HTML Code:
<form method="post" style="display: inline-block; margin-left: auto; margin-right: auto; text-align: left;">
<div style ="display:flex; align-items: baseline;">
Articles (EN)
<input type="text" name="articles_id_en" style="width: 30%;height: 22px;" value="<?php if($data->{"articles_id_en"}<>''){echo $data->{"articles_id_en"};} ?>">
Articles (FR)
<input type="text" name="articles_id_fr" style="width: 30%;height: 22px;" value="<?php if($data->{"articles_id_fr"}<>''){echo $data->{"articles_id_fr"};} ?>"><br>
</div>
<div style ="display:flex; align-items: baseline;">
Articles Entered (EN)
<input type="text"style="width: 30%;height: 22px;" value="<?php $values = $_REQUEST['articles_id_en']; $delimiter = ','; $valuesCount = count(explode($delimiter, $values)); echo "Values Count: " . $valuesCount . "<br>" . PHP_EOL; ?>">
Articles (FR)
<input type="text" name="articles_id_fr" style="width: 30%;height: 22px;" value="<?php if($data->{"articles_id_fr"}<>''){echo $data->{"articles_id_fr"};} ?>"><br>
</div>
<div>
<button type="submit">Save</button>
</div>
</form>
On hitting save, its get saved in a JSON as shown below with their list of values entered. At this moment, I have entered 149968, 149939, 149883, 149877, 149876, 149847, 154303 values so in JSON its showing like this:
{"articles_id_en":"149968, 149939, 149883, 149877, 149876, 149847, 154303"}
Below is the section of the screenshot of the form belonging to the above html/php code:
After entering the values, it display like this:
Following is the html code on inspect:
<input type="text" name="articles_id_en" style="width: 30%;height: 22px;" value=" 14996, 14993, 14988, 14987, 14987, 14984, 15430">
Problem Statement:
I am wondering what php code I need to add so that I can get the count of input values entered.

<form method="post">
<input type="text" name="articles_id_en" style="width: 30%;height: 22px;" value=" 14996, 14993, 14988, 14987, 14987, 14984, 15430">
<input type="submit">
</form>
<?php
if(isset($_REQUEST['articles_id_en'])) {
$values = $_REQUEST['articles_id_en'];
$delimiter = ',';
$valuesAsArray = explode($delimiter, $values);
$valuesCount = count($valuesAsArray);
} else {
$valuesCount = 0;
}
echo "Values Count: " . $valuesCount . "<br>" . PHP_EOL;
Have a look at this post about getting values from form
PHP function explode creates an array from the value="value1, value2" string that you get with $_GET['articles_id_en'];. The explode function creates an array with one entry per value that is separated with $delimiter character. Note that if values entered into form's input are separated with different character than , the solution will not work because explode looks for a specific character to divide a single string into multiple ones that it places inside an array.
count() just gives an integer number of items that it has between its () so if the array that is returned by explode() has 5 elements it will give an integer = 5.
result:
and after hitting submit:

First, convert your value data in an array using explode() and then count it using count().
if(isset($_POST['articles_id_en'])){
$value = $_POST['articles_id_en'];
$myArray = explode(',', $value);
echo $count_numbers = count($myArray);
}else{
echo "Form not submitted yet";
}

Here, we can also try and use preg_match_all that might work:
Notes:
We need to make sure, that each entry consists of valid digits, using i.e. this regex /([0-9]+)/m
However, it might be also the case where an entry contains a non-digit value in between, such as 149a93, in this case, we have to adjust our regex to overcome this problem by using word boundry, like so /(\b[0-9]+\b)/m
Then, our code might look like:
if(isset($_REQUEST['articles_id_en'])) {
$values = $_REQUEST['articles_id_en'];
$re = '/(\b[0-9]+\b)/m';
preg_match_all($re, $values, $matches, PREG_SET_ORDER, 0);
$count = sizeof($matches);
echo $count;
}
Demos
Regex: https://regex101.com/r/afKiC9/2
PHP: http://sandbox.onlinephpfunctions.com/code/07a370a52eb6c8d10cdbde9e2427af839a4a988a

Related

How do appending to associative array with variables work

i'm doing this exercise to understand te concepts and syntax of php.The error i get is that the array is not being appended by a new entry from a text box, if i hard code the values the program works fine and prints the array values. but as soon as i put the variable it just assign a new value to the [0] index.
here is the code:
<label for="Name">Student Name:
<input type="text" name="StdName" placeholder="Your name">
</label>
<label for="Name">Grade:
<input type="text" name="StdGrade" placeholder="Your Grade">
</label>
<input type="submit" name="submit"value="submit">
</form>
<?php
// Associative array new
$studentName = $_POST['StdName'];
$studentGrade = $_POST['StdGrade'];
$classGrades = Array();
$classGrades['name'][] = $studentName;
$classGrades['grade'][] = $studentGrade;
echo "<br> <br> Your name is: $studentName and your grade is: $studentGrade <br> <br>";
foreach($classGrades as $key=>$value){
echo join($value,' <br>');
}
?>```
Your loop is wrong. You have separate name and grade arrays, so that's what you need to loop over:
foreach ($classGrades['name'] as $index => $name) {
$grade = $classGrades['name'][$index];
echo "$name<br>$grade<br>";
}
But it would be better if you didn't create separate array and kept the name and grade together in a single associative array:
$classGrades[] = ['name' => $studentName, 'grade' => $studentGrade];
Then your loop would look like:
foreach ($classGrades as $grade) {
echo $grade['name'] . "<br>" . $grade['grade'] . "<br>";
}
If you want the variable to persist between form submissions, you need to use a session variable.
Put
<?php
session_start();
at the beginning of the script. Then use $_SESSION['classGrades'] instead of $classGrades, and initialize it like this:
if (!isset($_SESSION['classGrades'])) {
$_SESSION['classGrades'] = array();
}
Basically you need to store your values, in some database.
Here is a simple start using a json file named students.json as database. That file will be created along your php file in the same folder, if not existing.
First you was missing the form elements and the method (by default it uses GET, thus this was not working).
Testing with isset() avoids populating the database with empty values, at page load or refreshs.
This is not very secure as such, you will have to work on that later on. Hint: What if a user insert a quote ' or " in his name?
<form method="post">
<label for="Name">Student Name:
<input type="text" name="StdName" placeholder="Your name">
</label>
<label for="Name">Grade:
<input type="text" name="StdGrade" placeholder="Your Grade">
</label>
<input type="submit" name="submit"value="submit">
</form>
<?php
if (!is_file("students.json")){
file_put_contents("students.json", json_encode([]) );
}
$classGrades = json_decode(file_get_contents("students.json"),true);
if (isset($_POST['StdName']) && isset($_POST['StdGrade'])){
var_dump($classGrades);
$studentName = $_POST['StdName'];
$studentGrade = $_POST['StdGrade'];
$classGrades['name'][] = $studentName;
$classGrades['grade'][] = $studentGrade;
echo "<br> <br> Your name is: $studentName and your grade is: $studentGrade <br> <br>";
file_put_contents("students.json",json_encode($classGrades));
}
echo "<table><tr><th>Name</th><th>Grade</th></tr>";
for ($i = 0;$i < count($classGrades['name']);$i++){
echo "<tr><td>".$classGrades['name'][$i] . "</td><td> " .$classGrades['grade'][$i] . "</td></tr>";
}
echo "</table>";

Store values in database table using php explode function

I have a form with 4 or more checkboxes.The form is created by a while loop and has data from database table.Each checkbox represents a gift and each gift has a unique id (id1=1, id2=2, id3=3, ...) in database.So user can choose one or more gifts and click the submit button to store his choice.So I need php implode() function to get the string of what choices user made.For example if he chooses the 1st and the 2nd checkbox/gift the value that must be stored should be 1, 2.Instead of this I always have different stored data and don't match with user choices..Any ideas?
Form :
<form method='post' action='insert.php'>
.
.
.
while($row_select4 = $stmt_select4->fetch(PDO::FETCH_ASSOC)){
if($form_points>=$row_select4['points']) {
$points = $row_select4['points'];
echo '
<div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'">
<div class="feed-element">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="'. $row_select4['image_url']. '">
</a>';
?>
<button type="submit" id="submit" name="eksasrgirwsh" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>
</form>
Also (before insertion into table) :
if(isset($_POST['opt2'])){
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(", ", $sliced);
}
This is what I use to get the chosen gift_ids and create the string of them
Form updated:
<input type="hidden" disabled="disabled" name="opt2[]" value="'.$row_select4['id'].'">
Code for getting gift_ids:
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$gift_id = implode(", ", $gift);
}
No need for array_slice
in your php code:
$gift = $_POST['opt2'];
$gift_id = implode(", ", $gift);
By using this, you can get the result you wish.
Edit:
The reason you get all 1,2,3,4 is that you use hidden for gift id.
Try to add disabled="disabled" to the hidden tag which you dont want send to server. After this, you can get correct ids using $_POST['opt2']

Implode function doesn't store data as expected

I have already posted this but finally I didn't figure this out.I have a php form with some checkboxes (some of them are enabled and some disabled). Each of these has an id (id1=1, id2=2, id3=3, ...) which comes from database.
So when I submit the form I want to store these id's in a database table like this: if I choose only the 1st checkbox which has id=1 I should store '1' on my table and if I choose 1st and 3rd I should store '1, 3'. The problem is that I choose only the 1st and the stored data is '1, 2, 3, 4' because I have 4 checkboxes ENABLED.
PHP form :
<form method='post' action='insert.php'>
.
.
.
while($row_select4 = $stmt_select4->fetch(PDO::FETCH_ASSOC)){
if($form_points>=$row_select4['points']) {
$points = $row_select4['points'];
echo '
<div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'">
<div class="feed-element">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="'. $row_select4['image_url']. '"
</a>';
?>
<button type="submit" id="submit" name="eksasrgirwsh" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>
</form>
IMPLODE before insertion :
if(isset($_POST['opt2'])){
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(", ", $sliced);
}
And I store $gift_id in the table..
Check :
if(isset($_POST['opt'])){
$total_points = 0;
$points = array_values($_POST['opt']);
foreach ($points as $value) {
$total_points += $value;
}
echo $total_points;
$gift_ids = '';
$gift = array_keys($_POST['opt']);
foreach ($gift as $key => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
Instead of using separate hidden controls to store the ids, use the name property of the checkboxes to do this:
'...
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt['. $row_select4['id'].']" value="'.$points.'"></span>
...';
The name of a checkbox will be like name="opt[3]" for id 3 record.
In the php script processing the form submission array_keys($_POST['opt']) will give you the gift ids, while array_values($_POST['opt']) will return the points. You will know which point is associated with which gift id because the keys of the $_POST['opt'] are the gift ids.
Pls also note that storing multiple values in a comma separated string in a single field is not really considered a good practice. You should normalise your data structure and store the separate values in separate records.

How do I access two arrays from a form simultaneously in php?

I receive two arrays from a form. In the .php file, I need to insert the values of each array into a column of the table.
- use the foreach loop to access the elements of one array and complete the insertion for only one column. When I do the same thing for the next array, I find that the corresponding first column elements are null in each row while for the first array, the corresponding second column elements are null. Is there anyway to avoid this and insert the array elements one after the other?
- I understand that foreach cannot be applied to two arrays so is there any other way I can access both the arrays simultaneously for insertion into a table?
Thanks.
You can use a foreach loop:
foreach($_POST['someField_1'] as $key => $value)
{
$fieldOne = $value;
$fieldTwo = $_POST['someField_2'][$key];
}
Obviously change the _POST variables to whatever you've named the fields.
As long as your field names are named something like: name="someField_1[]" and name="someField_2[]" You can use the foreach loop in this way.
EDIT
Take this HTML for your input form:
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
So that form allows you to enter forenames and surnames for up to 3 people. Each field has the exact same name: forename[] and surname[]
To retrieve each of the values, you would use this PHP:
foreach($_POST['forename'] as $key => $forename)
{
echo 'Forename: ' . $forename;
echo ' ';
echo 'Surname: ' . $_POST['surname'][$key] . '<br />';
}
This works because when you submit a field like forename[], with square brackets at the end, PHP will automatically convert this to an array. $key is a number which starts at 0, and goes on for however many fields there are.
PHP uses the $key to retrieve the correct fields. You could also write your HTML like this:
Forename: <input type="text" name="forename[0]"> Surname: <input type="text" name="surname[0]">
Forename: <input type="text" name="forename[1]"> Surname: <input type="text" name="surname[1]">
Forename: <input type="text" name="forename[2]"> Surname: <input type="text" name="surname[2]">
You see I've put a number between the square brackets? PHP will detect this and loop through the arrays.
You could even use a for loop:
for($i = 0; $i<count($_POST['forename']); $i++)
{
echo 'Forename: ' . $_POST['forename'][$i];
echo 'Surname: ' . $_POST['surname'][$i];
}

bootstrap typeahead only showing first character of the result

Currently, my typeahead looks like this when I am creating it in php
echo '<input type="text" style="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="[,';
while ( $rowresult = mysql_fetch_assoc($titlequery) ) {
echo '{value:"'.htmlspecialchars($rowresult['title']).'"'."},";
}
echo ']">';
It outputs like this:
<input type="text" style="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="[,{value:"2010-11 Graf Intern"},{value:"2nd Year Finance Explorer, Mizani & L'Oreal Technique"},{value:"A&R Intern"},{value:"Account Executive"},{value:"Account Manager"},{value:"Account Service Representative"},{value:"Account Strategist"},{value:"Accountant"},{value:"Accounting Intern"},{value:"Accounting Intern/Analyst"},{value:"Accounts payable"},{value:"Acquisition Marketing Intern"},{value:"Acquisitions Associate"},{value:"Acting Manager"},{value:"Acting Software Manager"},{value:"Administrator"},{value:"Admissions Ambassador"},]">
Unfortunately, it only shows the first character of each value it is able to find (value being the default for bootstrap.)
Edit:
The question revolved around formatting results, in actuality, what was happening was Javascript was trying to reference an array that didnt exist, so it took the element [0] which was the first character to it.
Try to use this solution:
<?
$chars = array(":", "'", "?", '"', "/");
while ( $rowresult = mysql_fetch_assoc($titlequery) ) {
$Str = $rowresult['title'];
$Data[] = str_replace($vowels, "", $Str);
}
if(isset($Data)): ?>
<input type="text" style="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="[<?= implode(',', $Data) ?>]">
<?php endif; ?>

Categories