PHP: Function() check form indexed array - php

EDIT:
I solved my problem:
Thanks to all of you for your comment, it help me to think differently:
I didn't know that return ...; was behaving this way ( I believed it was just sending value not ending function ), so like I said, I'm just starting, I' a newbie...
I solved my problem with multidimensional array, I think it should work like I want now. I posted the code at the end of this post.
------------------------------------------------------------
I'm trying to make a basic checking form function that would be used to check all the form on my future website.It took me several hours (days...) to do this short code, because I'm a newbie in PHP, i just began few days ago.
Here is the Idea (Note that the form is way bigger I just created a smaller version of it for debugging).
PHP Library included with require() in the HTML page:
function check_form() {
$n = 0;
$indexed = array_values($_POST);
// How should I do to make this loop,
// to edit the HTML of each input one by one,
// without modifying other input that the one corresponding
// to the $n position in the table ?
if (isset($indexed[$n])) {
if (!empty($indexed[$n])) {
$value = $indexed[$n];
$icon = define_article_style()[0];
$color = define_article_style()[1];
} else {
$value = define_article_style()[4];
$icon = define_article_style()[2];
$color = define_article_style()[3];
}
$form_data_input = array($value, $icon, $color);
return $form_data_input;
}
}
The HTML Form:
<form role="form" method="post" action="#checked">
<div class="form-group <?php echo check_form()[1]; ?>">
<label class="sr-only" for="title">Title</label>
<input type="text" name="title" class="form-control input-lg" id="title" placeholder="Enter title * (min: 5 characters, max: 30 characters)" value="<?php echo check_form()[0]; ?>">
<?php echo check_form()[2]; ?>
</div>
<div class="form-group <?php echo check_form()[1]; ?>">
<label class="sr-only" for="another">Title</label>
<input type="text" name="another" class="form-control input-lg" id="another" placeholder="Enter title * (min: 5 characters, max: 30 characters)" value="<?php echo check_form()[0]; ?>">
<?php echo check_form()[2]; ?>
</div>
<button type="submit" class="btn btn-default" name="check_article" value="#checked">Check</button>
</form>
My problem is that the values returned to the inputs is always the content of "title", so for example if
$array[0] = $indexed[$index];
$array[1] = define_article_style()[0];
$array[2] = define_article_style()[1];
for "title" is equal to
$array[0] = "blabla";
$array[1] = "myclass1";
$array[2] = "myclass2";
every other input (in this case it's just "another") of the form have the same values.
I'm a bit confused, and I don't understand very well how everything works but I think this is related to the fact that the inputs share $array[n]to get their values/style but I don't really understand how I can keep this concept and make it work.
So if you understand what isn't working here I would be interested about explanation (keep in mind, I'm a newbie in code, and PHP.)
Thank you.
Greetings.
------------------------------------------------------------
Here is my working code ( I have to verify but I think it works correctly ).
function check_form() {
$n = 0;
$index_post = array_values($_POST);
while ($n < count($index_post)) {
if (isset($index_post[$n])) {
if (!empty($index_post[$n])) {
$value[$n] = $index_post[$n];
$color[$n] = define_article_style()[0];
$icon[$n] = define_article_style()[1];
} else {
$value[$n] = define_article_style()[4];
$color[$n] = define_article_style()[2];
$icon[$n] = define_article_style()[3];
}
}
$array_all = [$value, $color, $icon];
$n = $n + 1;
}
return $array_all;
}
Again, thanks for the answer, good to see that even newbies that don't understand half of what they do when they use this function over this other function get answers here.
Thumps up.
Greetings.

You have a lot of errors in your code:
First: I supose you have a view file "form.php" and the process for the submit form in "submit_form.php", so in your html code you need to fix this (action attribute):
<form role="form" method="post" action="submit_form.php">
Second: You have 2 input tags with names "title" and "another", so the $_POST array have 2 indexes:
$_POST["title"], $_POST["another"], you can check the content of this array:
var_dump($_POST); // this function print all the data of this array, check it.

Related

PHP->MySQL Form - Validation

I've got a dilema, I've got my database created, my input form works, however I'm looking to add validation to the POST so that certain things cant be entered, I can release snippets of code if needed however I can't find what I'm looking for.
My form basically
<input type="text" name="id1" placeholder="Pick a number">
<input type="text" name="id2" placeholder="Pick another number">
However, I would like to display an error if they pick the same number
EG: IF ID1 == ID2 then ECHO error.
However I'm unsure of the code, I have a simple PHP Mysql form.
You can use this code:
if($_POST['id1'] == $_POST['id2']) {
echo 'error';
}
on the action of your form i.e you define in your action attribute of form action='somepage.php write below code.
if(isset($_REQUEST['id1']) && isset($_REQUEST['id2'])){
if($_REQUEST['id1'] >= $_REQUEST['id2']){
echo "error";
}
}
To be sure, use typecasting plus check if posts are set.. e.g.
<?php
$id1 = isset($_POST['id1']) ? (int) $_POST['id1'] : 0;
$id2 = isset($_POST['id2']) ? (int) $_POST['id2'] : 0;
if(!empty($id1) && !empty($id2) && $id1 !== $id){
// success
} else {
// fail
}

Increase/decrease parameter in query parameter $_GET through links

Recently, I started to learn PHP through some course I found on my college website (don't worry, this is not homework, I'm doing this on my own)
and I'm stuck. The assignment goes like this:
Create a page with two links, one for increasing and one for decreasing parameter 'n' which should be accessed through $_GET query parameter. If 'n' is not set, assume it's value is 4.
So, I tried something like this (just for increasing at first):
<form action="<?php $_PHP_SELF ?>" method="GET">
<input type="hidden" name="n" value="4">
<input type="submit">
</form>
and my PHP code goes like this:
<?php
$var = 4;
if(!isset($_GET['n'])) {
$_GET['n'] = $var;
} else {
$var = $_GET['n'];
$var++;
$_GET['n'] = $var;
}
echo $_GET['n'];
?>
But this does not seem to work, at all. I'm guessing the 'n' should automatically change in the URL too. Also, how can I have to "submit" buttons, one for increase, one for decrease?
Can anyone help (with some good instructive explanation if possible) and if it's possible to make it with just HTML links because the course didn't go through forms yet.
in the form code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
<input type="hidden" name="n" value="<?php echo $var; ?>">
<input type="submit">
</form>
EDIT
to make it increase / decrease:
<?php
if(!isset($_GET['n'])) {
$var = 4;
} else {
$var = $_GET['n'];
}
echo 'Value = ' . $var;
?>
<p>
Increase
Decrease
</p>
Your PHP code could be simplified to the following:
if (!isset($_GET['n'])) {
$_GET['n'] = 4;
}
$_GET['n']++; // you can do that
However, you probably won't want to increment or decrement $_GET['n'] directly. Try keeping just the if part, then incrementing or decrementing when you output the link:
<?php
if (!isset($_GET['n'])) {
$_GET['n'] = 4;
}
?>
increment n
decrement n
Note that don't need a form to pass parameters through $_GET or $_POST — you can just build a URL that passes a parameter, like I did here.

How to use a Chunk and a Snippet in a Resource, but returning only the Chunk when page is loaded using MODx Revolution?

I have a resource (63) that should get a value from a form (chunk) which will be later handled by a snippet that divides it by 4. Than it gives me the result on the same page as you can see below:
In the resource:
[[$divisionForm]]
[[!divisionFormHandling]]
The divisionForm Chunk:
<form action="[[~63]]" method="post">
<input type="text" name="value"/>
<input type="submit" name="division" value="Submit" />
</form>
The divisionFormHandling snippet:
<?php
$var = $_POST["value"];
$division = $var / 4;
if ($division != 2) {
$error_message = 'It is not the number 8!';
$output = $error_message;
return $output;
}
else {
$playing_around = $var + 1;
}
working_around = $var * 2;
$output = 'Playing: '.$playing_around.'<br />';
$output .= 'Working: '.$working_around.'<br />';
return $output;
?>
So, when I insert 8 in the form and submit it, I have following result on the screen:
Playing: 9
Working: 16
And when I insert any other number I have the following result, just like expected:
It is not the number 8!
But when I access the page for the first time or refresh it, I still receive the error_message. My problem is: how could I rewrite the code, so at the first time or after a refresh I see only the form (i.e. the Chunck) and not the error message (that comes from the Snippet)?
I'm quite sure that there is a cleaner way to do this, but I need help.
Many thanks!
if (isset($_POST["value"])) { // here first time checking
$var = (int) $_POST["value"]; // (int) is for security purpose
// all other your code here ...
}

Any ideas why this wont print out

Revising for php and cant seem to get this to print the values out that i want
Any ideas?
Thanks
<form action="revision.php" method="GET">
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type=“text” name=“number[]”/>
<input type="Submit" name="Calcuate"/>
</form>
<?php
if(isset($_GET['number'])){
$amount = count($number);
for($i=0; $i < $amount; $i++){
echo $number[$i];
}
}
?>
I think the actual problem with your code is that the quotation marks " are wrong you are using “ and ” instead of ". Replace those and everything will work.
EDIT: My answer is completely wrong. See #rmarimon in comments below.
Text fields can't be mapped to an array. You'll have to name them something ugly like "number1", "number2", etc and add them up with $_GET['number1'] + ...
<form action="revision.php" method="GET" enctype="multipart/form-data">
Change form to this.
The multipart tag must be used for this
you also need this for file uploads
and for printing use this
foreach ($_GET['number'] AS $key => $value)
{
echo "$key => $value";
}
because the array can be number[1] -> number[3]
It is not in your code but do you have
$number = $_GET["number"]
What you are doing is the correct way. This is similar to this other question.
The way I see it, there's a couple things you should change in your code, first, the names of the fields, you're trying to name them number[0], number[1], number[2] from the looks of it but it won't work that way, try naming them differenty or try to make a FOR cicle to create the fields with those custom names. Second, in order to save the array coming in the $_GET variable into the $number variable you need something like this:
if(isset($_GET['number']))
{
$number = $_GET['number'];
$amount = count($number);
for( $i = 0 ; $i < $amount ; $i++ )
echo $number[$i];
}
Hope this helps, if you're still having problems try posting or describing the context and what you have in mind for the form and the array.

A form that spits out the input

I can't for the life of me find a form that doesn't email the results that you submit.
I'm looking to find a form that I can have users enter simple data that i can then spit back out at them in different arrangements. If they submit First and Last, I'll spit out, amongst other things, FirstLast#domain.com. I'm willing to scrounge the code manually to do this, but I cant find a simple form that would allow me to do this.
Edit: PHP or similar simple languages. I've never touched .NET before.
Form:
<form action="process.php" method="post">
First: <input type="text" name="first" />
Last: <input type="text" name="last" />
<input type="submit" />
</form>
Next page:
<?php
$first = $_POST['first'];
$last = $_POST['last']
echo $first . "." . $last . "#domain.com";
?>
See http://www.w3schools.com/php/php_forms.asp for more examples and explanation
Regardless of how you get it, always remember to never trust user input.
<?php
$sfirst = htmlentities($_POST['first']);
$slast = htmlentities($_POST['last']);
echo $first . "." . $last . "#domain.com";
?>
Also, running a validator on the final result may be helpful. But please don't write your own email address validator.
What language/platform/environment are you working in?
I guess you might be looking for a hosted script or webform (the way that people will host web-to-mail scripts I suppose) but I doubt there would be one out there that does this.
But if you have a specific framework to work in, e.g. PHP or .net, please update the question and let us know which.
Thing that simple doens't even need server-side support.
<form onsubmit="magic(this);return false">
<p><label>First <input name=first/></label>
<p><label>Last <input name=last/></label>
<input type="submit">
<div id="output"></div>
</form>
<script type="text/javascript">
var output = document.getElementById('output');
function toHTML(text)
{
return text.replace(/</g,'<');
}
function magic(form)
{
output.innerHTML = toHTML(form.first.value + form.last.value) + '#domain.com';
}
</script>
If I get your question right, sounds like this might do what you need..
Note: This PHP code doesn't require any knowledge of the fields in the form that submits to it, it just loops through all of the fields, including multiple-choice fields (like checkboxes), and spits out their values.
<?php
// loop through every form field
while( list( $field, $value ) = each( $_POST )) {
// display values
if( is_array( $value )) {
// if checkbox (or other multiple value fields)
while( list( $arrayField, $arrayValue ) = each( $value ) {
echo "<p>" . $arrayValue . "</p>\n";
}
} else {
echo "<p>" . $value . "</p>\n";
}
}
?>

Categories