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.
Related
I have a anchor tag:
Count Click
I want to count number of times this link has been clicked.
In abc.php I use the following code but it is not working:
$b = $_GET['a'];
$b += 1;
echo "Number of Times Clicked=".$b;
EDIT
Use a POST instead;
$a = intval($_POST['a']);
session_start();
$b = intval($_SESSION['clickCount']);
$b += $a;
$_SESSION['clickCount'] = $b;
session_write_close();
You should store the value of this variable somewhere, because when you send GET request the page is refreshing and your value is missing.
You can store this value in session. See http://php.net/manual/features.sessions.php
or cookies see http://php.net/manual/features.cookies.php or in some database on server.
And then get it from there.
First of all recommend you to store values in $_SESSION and also use $_POST
Why use $_SESSION & $_POST? because no one can mess up with your application.
Basic Example (PHP):
<?php
session_start();
$varCount = 0;
if(isset($_POST['submit'])){
$var = intval($_POST['var']);
$addVar = $var+1;
$_SESSION['newVar'] = $addVar;
}
else{
unset($_SESSION['newVar']);
}
if(isset($_SESSION['newVar'])){
$varCount = intval($_SESSION['newVar']);
echo $varCount;
}
?>
HTML:
<form method="post" action="">
<input type="hidden" name="var" value="<?=$varCount?>">
<input type="submit" name="submit" value="Add">
</form>
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.
I am building a number guessing game and need to create a session variable to hold the randomized target number until the user submits the correct guess. I also need to print the number of attempts after the user submits the correct answer.
I set my session variable and used a hidden field to hold the counter. I don't know if the hidden field works bc when I submit a guess, my code prints out the first if statement of the check() function..ALL THE TIME.
I think it has something to do with the session variable (and of course my code), but I can't figure it out. I've been working on this for two days now and feeling the frustrations. Any help would be amazing. Here's my full code below:
<?php session_start() ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Number Guessing Game</title>
</head>
<body>
<h1>Guess the number</h1>
<p>I'm thinking of a number between 1 and 5. Can you guess what it is?<br>
In less than 3 tries?</p>
<?php
extract($_REQUEST);
error_reporting(E_ALL & ~E_NOTICE);
// check to see if this is start of game
if (filter_has_var(INPUT_POST, "guess")) {
check();
} else {
setTarget();
} //end if
// set targetNum session variable
// increment counter by 1
function setTarget() {
$targetNum = rand(1, 5);
$_SESSION["targetNum"] = $targetNum;
$counter++;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
}
function check() {
global $counter;
print <<<HERE
<form action="" method="post">
<input type = "text"
name = "guess"
value= "$guess">
<input type = "hidden"
name = "counter"
value = "$counter">
<h2>Target Number: $targetNum</h2>
<h3>The counter is at: $counter</h3>
<br>
<button type = "submit">
SUBMIT GUESS
</button>
</form>
HERE;
if ($guess == $_SESSION['$targetNum']) {
print "<h3>Awesome. You guessed it in $counter attempt(s)</h3>";
unset($_SESSION["targetNum"]);
$count = 0;
print "<a href='numberGuessingGame.php'>TRY AGAIN</a>";
} else if ($guess > $_SESSION['$targetNum']) {
print "<h3>Too high. Guess again.</h3>";
} else if ($guess < $_SESSION['$targetNum']) {
print "<h3>Too low. Guess again.</h3>";
} else {
print "I don't know what that is...";
}
}
?>
</body>
</html>
You made two basic, but severe errors.
First: DO not set the error level to exclude notices when developing! That way you will never spot typos in variable or array index names. Remove error_reporting(E_ALL & ~E_NOTICE);, or replace it with error_reporting(E_ALL);.
Second: You use extract($_REQUEST); - using that function is asking for trouble. PHP has a long history of security vulnerabilities because of the "register_globals" feature, which introduces global variables just because some key=value pair in the request data was parsed. It took years to remove that feature. You are re-implementing it without any security precaution by using that function, and with no real benefit.
Remove that extract($_REQUEST); function, and use $_REQUEST['varname'] instead of $varname for all variables that come from the remote browser.
Your $guess variable is never set to the POST value (Correction: you're using extract but I'd advise against it). You are also changing the value of your session array key when you add a '$':
$guess = $_POST['guess'];
if ($guess == $_SESSION['targetNum']) {
I've been looking for the solution of my problem for ages and I still haven't found it so i desided to create a stackoverflow account to ask the question myself.
this is what I created so far:
<? //Chooses a random number $num = Rand (1,2);
switch ($num){
case 1: $retrieved_data = "test"; break;
case 2: $retrieved_data = "test1"; break;
} ?>
And this is the place where I want the text to appear;
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input type="submit" value="Upload" /></form>
My problem is I want to have the "test1" and "test" randomly displayed on these places
but I want them to be different from eachother every time. So if the first input type is "test" I want the second input type to be 'test1" but I can't seem to get this working
Does anyone know what I'm doing wrong or a code to make this possible?
If you have limited number of possibilities, put them int an array, shuffle it and shift/pop elements from it:
$retrieved_data = array('test', 'test1');
shuffle($retrieved_data);
$random1 = array_shift($retrieved_data);
$random2 = array_shift($retrieved_data);
Step A - you are selecting a number, 1 or 2
Step B - you are running that number through your switch case, this case ONLY takes the number that it receives and assigns it a value. Therefore if your number is 1, your switch case ends at $retrieved_data = "test". If your number is 2 your switch case goes to case 2 and assigns $retrieved_data = "test 1".
Step C = $retrieved_data is assigned to your form (it will have only one value, "test" or "test1".
Use array_rand() for that.
$aName = array('test1', 'test2', 'whatever');
function getRandom(array &$aName)
{
if (($key = array_rand($aName)) === NULL) {
throw new Exception('No more randomness!');
}
$value = $aName[$key];
unset($aName[$key]);
return $value;
}
So simply use getRandom($aName) when you need a unique random item from the array.
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.