I'm absolute beginner in web technologies. I know that my question is very simple, but I don't know how to do it.
For example I have a function:
function addNumbers($firstNumber, $secondNumber)
{
echo $firstNumber + $secondNumber;
}
And I have a form:
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
How can I input variables on my text fields and call my function by button pressing with arguments that I've wrote into text fields?
For example I write 5 - first textfield, 10 - second textfield, then I click button and I get the result 15 on the same page.
EDITED
I've tried to do it so:
$num1 = $POST['number1'];
$num2 = $POST['number2'];
addNumbers($num1, $num2);
But it doesn't work, the answer is 0 always.
The "function" you have is server-side. Server-side code runs before and only before data is returned to your browser (typically, displayed as a page, but also could be an ajax request).
The form you have is client-side. This form is rendered by your browser and is not "connected" to your server, but can submit data to the server for processing.
Therefore, to run the function, the following flow has to happen:
Server outputs the page with the form. No server-side processing needs to happen.
Browser loads that page and displays the form.
User types data into the form.
User presses submit button, an HTTP request is made to your server with the data.
The page handling the request (could be the same as the first request) takes the data from the request, runs your function, and outputs the result into an HTML page.
Here is a sample PHP script which does all of this:
<?php
function addNumbers($firstNumber, $secondNumber) {
return $firstNumber + $secondNumber;
}
if (isset($_POST['number1']) && isset($_POST['number2'])) {
$result = addNumbers(intval($_POST['number1']), intval($_POST['number2']));
}
?>
<html>
<body>
<?php if (isset($result)) { ?>
<h1> Result: <?php echo $result ?></h1>
<?php } ?>
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
</body>
</html>
Please note:
Even though this "page" contains both PHP and HTML code, your browser never knows what the PHP code was. All it sees is the HTML output that resulted. Everything inside <?php ... ?> is executed by the server (and in this case, echo creates the only output from this execution), while everything outside the PHP tags — specifically, the HTML code — is output to the HTTP Response directly.
You'll notice that the <h1>Result:... HTML code is inside a PHP if statement. This means that this line will not be output on the first pass, because there is no $result.
Because the form action has no value, the form submits to the same page (URL) that the browser is already on.
Try This.
<?php
function addNumbers($firstNumber, $secondNumber)
{
if (isset($_POST['number1']) && isset($_POST['number2']))
{
$firstNumber = $_POST['number1'];
$secondNumber = $_POST['number2'];
$result = $firstNumber + $secondNumber;
echo $result;
}
}
?>
<form action="urphpfilename.php" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<?php addNumbers($firstNumber, $secondNumber);?>
<p><?php echo $result; ?></p>
<p><input type="submit"/></p>
You need to gather the values from the $_POST variable and pass them into the function.
if ($_POST) {
$number_1 = (int) $_POST['number1'];
$number_2 = (int) $_POST['number2'];
echo addNumbers($number_1, $number_2);
}
Be advised, however, that you shouldn't trust user input and thus need to validate and sanitize your input.
The variables will be in the $_POST variable.
To parse it to the function you need to do this:
addNumbers($_POST['number1'],$_POST['number2']);
Be sure you check the input, users can add whatever they want in it. For example use is_numeric() function
$number1 = is_numeric($_POST['number1']) ? $_POST['number1'] : 0;
Also, don't echo inside a function, better return it:
function addNumbers($firstNumber, $secondNumber)
{
return $firstNumber + $secondNumber;
}
// check if $_POST is set
if (isset($_POST['number1']) && isset($_POST['number2']))
{
$number1 = is_numeric($_POST['number1']) ? $_POST['number1'] : 0;
$number2 = is_numeric($_POST['number2']) ? $_POST['number2'] : 0;
echo addNumbers($_POST['number1'],$_POST['number2']);
}
You are missing the underscores in
$_POST['number1']
That's all.
maybe it's a little late
but could you set a parameter in the url of the php file to post example:
In the html :
...
<form action="Controllers/set_data.php?post=login" method="post" >
...
In the php :
...
$post_select = $_GET['post'];
switch ($post_select) {
case 'setup':
set_data_setup();
break;
...
You can always use this trick. But keep in mind that if the referrer is hidden it doesn't work.
header("Location: " . $_SERVER["HTTP_REFERER"]);
Just add to your PHP page at the point where there is no more code to be executed, but is still executed.
Related
I'm trying to make a simple form that is validated and errors should be shown. Also, the values of the fields should stay.
I'm using simple routing code to determine which page to show.
My problem is that the values of the form always reset when I submit it.
I googled a bit and found that when the Request changes, the form values get lost.
That's a small example that shows what I want to achieve:
$route = $_SERVER['REQUEST_URI'];
switch ($route) {
case '/kontakt':
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test">
<input type="submit">
</form><?php
break;
}
After submitting the entered value should stay in the field.
So how can I keep the Request when routing to the same route but one time with POST and one time with GET without changing the form value to use the _POST array?
Lets first grab which request we need to use to get the request arguments.
$request =& $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
It would probably be a good idea here to check it is set, if it isn't - just leave it blank.
$name = $request['name'] ?? ''; # PHP 7+
$name = isset($request['name']) ? $request['name'] : ''; # PHP 5.6 >
You can then do your routing
# switch: endswitch; for readability
switch(($route = $_SERVER['REQUEST_URI'])):
case '/kontack': ?>
<form method="POST" action="/kontakt">
<input type='text' value='<?= $name; ?>' name='name' />
....
<?php break;
endswitch;
This will then continuously insert the name back in to the value field. However, if you visit a new page and then come back - it will be gone. If you want it to stay at all times, through-out any route, you can use sessions.
session_start();
# We want to use the request name before we use the session in-case the user
# Used a different name to what we previously knew
$name = $request['name'] ?? $_SESSION['name'] ?? ''; # PHP 7
$name = isset($request['name']) ? $request['name'] : isset($_SESSION['name']) ? $_SESSION['name'] : ''; # PHP 5.6 >
# Update what we know
$_SESSION['name'] = $name;
Note: I showed both PHP 5.6> and PHP 7 examples. You only need to use one based on which PHP version you're using.
When you are getting to the route in the first time, then send a HTML-valueAttribute-variable as null. When you go back to the route after posting send the post value to the HTML-valueAttribute-variable:
When you reach the route the first time:
<?php
//Value that is sent to the view/page when accessing route without having posted a value
$testValue=null
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>
When you use the route after have posted:
<?php
//Value that was posted is sent to view/page
$testValue=$POST['test']
?>
<form method="POST" action="/kontakt">
<input type="text" required name="test"
<?php
if($testValue != null)
{
echo "value='".$testValue."'";
}
?>
>
<input type="submit">
</form>
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.
I am trying to create a little php programme where I enter text into a text field. I then want the text to be added to an array. I do this by calling a function when the 'Add' button is clicked. After the button is clicked, I want the array entries to be displayed and the number of entries too. Here is the code I have so far, but it doesnt work :P
I have tried a few things, but nothing seemed to work.
I changed it to this now:
<form action="array.php" method="POST">
<fieldset>
<legend>Enter text here</legend>
<p>text: <input type="text" size="60" name="text"></p>
<p><input type='button' name='add' value='Add' onclick= "<?php add() ?>"></p>
</fieldset>
</form>
<?php
global $array;
$array = array();
function add()
{
if(isset($_POST['text']))
{
array_push($array, $_POST['text']);
}
return $array;
}
$arraystring = implode(", " , $array);
echo $arraystring;
?>
You have a couple of problems here. First:
<script>
function add_script(){
alert("<?PHP add(); ?>");
}
</script>
The alert does not make sense here. You cannot pass data between javascript and php like that. What you would need is AJAX. The easiest solution would be Jquery's ajax function. So you would need to set up a function to handle the data, a separate php script to receive it and process it and your safest bet is to return a JSON string which the initial script would process, read and return the data.
The second very big problem is the add() function - a function may not return more than one value. Whenever the interpreter sees
return $x;
The function will stop there and return whatever you've given it. The second will be ignored as the function has been terminated.
Your second option would be to post the entire form to the same script
<form method="post">
<!--the form inputs here-->
</form>
and when the "Add" button is clicked it will post the entire data to itself. and then in the PHP script you would need to add a condition to handle the case:
<?php
if($_POST && $_POST['text']) echo $_POST['text'];
?>
To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>
I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>