Change foreach $key variable inside the foreach loop - php

Looking for a way to change $$key to something like $$key_errorso the variable will look something like: $name_error outside the foreach loop.
Here is what I have so far:
foreach ($_POST as $key => $value) {
$$key = strip_tags(mysqli_real_escape_string($mysqli, $value));
if (empty($value)) {
// change variable below to something like $$key_error ($$name_error)
$$key = 'is-invalid';
} else {
$$key = "value='$value'";
}
}
When an input is empty the user will return to the registration form, the input that is empty will have red bootstrap borders. When a field is not empty, the value will still be there so they do not have to do it all over.
<input type="text" name="name" class="form-control form-control-lg <?=$name?>" style="text-align:center;" placeholder="Voor- en achternaam" <?=$name?>>
I hope it all makes sense :)

Use arrays.
$errors = [];
$values = [];
foreach ($_POST as $key => $value) {
// validation check for $value
if (/*validation check fails*/) {
$errors[$key] = 'error message specific to this field';
} else {
$values[$key] = htmlspecialchars($value);
}
}
Then in your form, check for the array key matching your control name.
<input type="text" name="example"
class="<?= isset($errors['example']) ? 'is-invalid' : '' ?> other classes"
value="<?= $values['example'] ?? '' ?>">
You can also output the specific error message if you want to.
<div class="error"><?= $errors['example'] ?? '' ?></div>

Related

Foreach - How to print a only the third and 4th value

I have form with the option to add more fields.
I'd like to know if i could print the individual values of a foreach loop.
eg. if the person added to forms and i want to print the second value how would i do that ?
So Far what i have tried only printed the first Character.
HTML
<form action="careerHistoryCon.php" method="post" enctype="multipart/form-data">
<label for="industry[]">Industry Segmentation</label>
<input type="text" name="industry[]" id="" placeholder="Finance / Insurance ...."><br>
<p>To add another feild Click here </p> <br><br>
</form>
JQ
$("#addMore").click(function(){
$(".form-group:last").clone().appendTo(".wrapper");
});
PHP - Problem here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])){
$industry= $_POST['industry'];
foreach ($industry as $key => $value) {
echo $value[0]. '<BR>';
echo $value[1]. '<BR>';
}
}
You are pretty near to the solution. Using foreach on an array gives you the index as key.
foreach ($industry as $key => $value) {
if($key == 1) echo $value; // array starts with 0, so 1 is the second element.
}
or you can use an iterator
// using foreach
$i = 0;
foreach ($industry as $key => $value) {
if($i == 1) echo $value;
$i++;
}
//using for
for($i = 0; $i < count($industry); $i++) {
if($i == 1) echo $industry[$i];
}
btw. since $value is the input string of the user, $value[0] would just be the first letter the user entered. Because a string is just an array of chars.

Obtaining $_SESSION array values and displaying using echo

I have the ff code which stores values inputted in form's textfield to a session array which I named "numbers". I need to display the value of the array but everytime I try echo $value; I get an error Array to string conversion in
I used echo var_dump($value); and verified that all the inputted values are stored to the session array.
My goal is to store the user input to an array everytime the user hits the submit button.
How do I correct this?
<?php
session_start();
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="index.php">
<label>Enter a number</label>
<input type="text" name="num" required />
<button type="submit">Submit</button>
</form>
</body>
</html>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$_SESSION['numbers'][] = $_POST["num"];
foreach($_SESSION as $key => $value){
echo ($value);
}
}
?>
Thank you.
When doing $_SESSION['numbers'][] = $_POST["num"];, you are making $_SESSION['numbers'] an array: so you'll either need to do that differently, or check whether $value within your foreach loop is an array or not.
if (isset($_POST["num"]) && !empty($_POST["num"])){
$_SESSION['numbers'][] = $_POST["num"];
foreach($_SESSION as $key => $value){
if (is_array($value)) {
foreach ($value as $valueNested) {
echo ($valueNested);
}
} else {
echo ($value);
}
}
}
OR
if (isset($_POST["num"]) && !empty($_POST["num"])){
$_SESSION['numbers'] = $_POST["num"];
foreach($_SESSION as $key => $value){
echo ($value);
}
}
The latter is probably what you are actually trying to accomplish.
If you want to echo all entered numbers, your for each cycle should be:
foreach($_SESSION[‘numbers’] as $key => $value) {
echo $value;
}
This is because the $_SESSION[‘numbers’] itself is the array that contains the numbers.
The error is because SESSION[“numbers”] is an array and you can just echo an array. It will throw an error “Array to string converstion”.
Iterate through the array and print it instead.

How do I make it so a Variable = whats in a text box/text field?

How do I make it so a Variable = whats in a text box/text field?
for example my text-field looks like this.
<input type="text" name="key" class="form-control" >
and my variable looks like this.
$key
Try following code:
foreach($_POST as $key=>$value)
{
${$key} = $value; echo $key;
}exit;
if (isset($_POST['key'])) {
$key = $_POST['key'];
}
Much easier way.

Getting both or one Checkbox value in for each loop

I have a form that the user can submit either 1 or 2 checked boxes. It must be at least 1. The checkbox setup looks like so:
<input name="request['+fields+'][Type of Folder:]"
id="cbpathCDB'+fields+'" type="checkbox"
value="Content Database" class="cbShowPath required" data-id="'+fields+'"/>
<input name="request['+fields+'][Type of Folder:]"
id="cbpathEFS'+fields+'" type="checkbox"
value="File System" class="efsShowPath required" data-id="'+fields+'"/>
There is other inputs that are also being submitted, so I am using this for each:
$a=$_REQUEST['request'];
foreach ($a as $name) {
foreach ($name as $key => $desc) {
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
This gets all the data fine if the user checks ONE checkbox, but if the user checks both checkboxes, only the value of the FIRST checkbox is shown.
What do I need to do here in order to get both values?
Do I need a 3rd foreach in here to get name="request[][][]"?
EDIT: some updates here...
If I use his foreach:
foreach ($a as $name) {
foreach ($name as $key => $desc) {
foreach ($desc as $d){
$note.= $key;
$note.= $d;
}
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
I get these results echoed out:
Type of Folder:Content DBType of Folder:File SystemType of Folder:Array
If I use his foreach:
foreach ($a as $name) {
foreach ($name as $key => $desc) {
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
I get these results echoed out:
Type of Folder:Array
Change the name of the form elements to
request['+fields+'][Type of Folder:][]
So for your code
<input name="request['+fields+'][Type of Folder:][]" id="cbpathCDB'+fields+'" type="checkbox" value="Content Database" class="cbShowPath required" data-id="'+fields+'"/>
<input name="request['+fields+'][Type of Folder:][]" id="cbpathEFS'+fields+'" type="checkbox" value="File System" class="efsShowPath required" data-id="'+fields+'"/>
This will make $_REQUEST['request']["'+fields+'"]['Type of Folder:'] an array containing the value of each checked box.
You need to modify the part of your code working with $desc to include another loop.
foreach ($a as $name) {         
foreach ($name as $key => $desc) {
switch (gettype($desc)) {
case 'array':
foreach ($desc as $i => $item) {
$note .= "{$key}[{$i}]";
$note .= $item;
}
break;
case 'string':
default:
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
}

Looking for a way to store the result of a form field with dynamic name and id in an array after submit

I'm building a form which has the following fields:
$k = 1;
foreach($ui_fmlSect_pg as $val)
{
$url_arr[] = $val;
echo '<tr>';
echo '<td><input size="1" type="text" name="freq_'.$k.'" id="freq_'.$k.'"
value="'.$udf_fmlS.'"></td></tr>';
++$k;
}
I would like to find a way to add the entered values, that is the content of the variable $udf_fmlS or any manual overwriting, from the *freq_$k* -named input fields into an array, but I'm not sure how to proceed with this, especially as the name and id are dynamically generated.
Thanks in advance for your help
You could do something like this:
$freq = array();
foreach ($_POST as $key => $val) {
// check for submitted data starting with freq_
if (substr($key, 0, 5) == 'freq_') {
// use the number after freq_ as the key and the value as the value
$freq[substr($key, 5)] = $val;
}
}
If I understand correctly, you will have variables like:
$_REQUEST['freq_0']
$_REQUEST['freq_1']
etc. You could do something like:
<?php
$freq_val_arr = array();
foreach($_REQUEST as $key => $val){
if (strpos($key, 'freq') === 0){
$freq_val_arr[] = $val;
}
}
Just change 'file_'.$k to 'file[]' or to 'file[' . $k . ']'

Categories