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.
Related
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 have an array something like this
$steps = explode("[;;]",$str);
So the $steps holds value that I have to use to show a step/step procedure in PHP .
The array looks like this
$steps = array('corredores' , 'something' , 'something'...and so one );
I am trying to display forms according to the value saved in the array . I am able to go forward using some validation but I have trouble in moving to the previous name in the array ,
for the first step I am doing something like this
$steps = explode("[;;]",$_POST['str']);
$x = explode("=",$steps[0]);
$pais1 = $_POST['pais'];
$cnt=0;
switch($steps[0]){
case 'categorias' :
include 'obj/categorias.php';
//$step='categorias';
break;
case 'corredores':
include 'obj/corredores.php';
//$step='corredores';
break;
case 'monedas':
include 'obj/monedas.php';
//$step='monedas';
break;
case 'location':
include 'obj/location.php';
//$step='location';
break;
default:
break;
}
//Here I am trying to match the next value from the array that I will save in this post value on every step
if(isset($_POST['next1']) &&$_POST['method'] != "fase1")
{
$cnt =$_POST['cnt'];
$cnt++;
$array_var = unserialize(base64_decode($_POST["next1"]));
$steps = $array_var;
$pais1 = $_POST['pais'];
$x = explode("=",$array_var[$cnt]);
include 'obj/'.trim($x[0]).'.php';
//$step='categorias';
}
So when I click on the next button of each file it goes to the next file in the array , But Now I need to add similar functionality to the previous button so that it goes back
The HTML content of every files has following structure
<form method="post" action="./index.php" name="form_name">
<table><tr><th>Some Name</td></tr>
<tr><td><input type="submit" value="previous"></td><td><input type="submit" value="next"></td></tr></table>
<input type="hidden" name="next1" value="<?php print base64_encode(serialize($steps)) ?>">
<input type="hidden" name="pais" value="<?php echo $pais1?>"/>
<input type="hidden" id="cnt" name="cnt" value="<?php echo $cnt ?>" />
</form>
Can any one give me some suggestion
Thanks in Advance
If I am not reading your code wrong, you already have an array of all the objects stored in next1 and cnt as your currently counter. Essentially, what you need to do is to detect whether the user has pressed the Next or Previous button
<input type="sumbit" name="next" value="Next">
<input type="submit" name="previous" value="Previous">
A form can have more than 1 submit button. Just be sure to name them differently. Then when you process your form:
if (isset($_POST['next'])) {
// go on to the next object
$cnt = $_POST['cnt'] + 1;
} else if (isset($_POST['previous']) {
$cnt = $_POST['cnt'] - 1;
}
// retrieve object from array and include its file
It is important that you don't increment your cnt like above -- and only increment or decrement it before you press the buttons.
In short, change the value of cnt depending if the user presses Next or Previous.
You can use array_search http://php.net/manual/en/function.array-search.php for identifying acual step and then Add +1 for next step or remove -1 for the previous step
how to make something like a random lottery. Very simple, in the fact that it shouldn't be long code.
I just want a form that i user can click a radio button which equals 1 and enter their name. When they submit $min = 1(and stays at 1), $max = $max + 1.
Lets say 10 people select the radio button and hit the first submit button. $min = 1 meaning the lowest random number is 1. Then their name is put into an array along with a matching id corresponding to the number in the variable $max(if 5 people submitted, the $max would be 5, and their id would also be 5 as they submitted fifth.
So if 10 people submit , and then click another submit button below a random generated number will be made with a minimum of $min which is 1 and a maximum of $max (the last person to submit radio button).
if the random generated number was 7, then display the 7th person that submitted the radio button(because their id would match with the random number).
I have been learning php for 2 weeks so im not very good now, but my code goes like this...
<form action="POST" name="form">
<input type="text" name="name">
<input type="radio" name="1" value="1">
<input type="submit" name="submit" value="submit">
</form>
<?php
$min = "";
$max = "";
$person = array();
for($_SERVER["REQUEST_METHOD"] == "POST"){
$max = $max + 1;
$person[$max] = $_POST["name"] . ;
$min = 1;
}
?>
<form action="POST" name="random">
<input type="submit" value="submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST" && $_POST["name"] == "random"){
$rand=------rand($min,$max);
if(//TODO) {
$person[$]
}
}
?>
can someone explain how to make this work please?
Assuming you store everything to a MySQL database a possible solution to retrieve a lottery winner would be:
$DB_winner = mysql_query("select name from participants_table_name");
while($win = mysql_fetch_array($DB_winner){
$winners[] = $win['name'];
}
// and the winner is $the_winer:
$the_winner = $winners[rand(0, sizeof($winners)-1)];
I was going to post a comment but it's busy with trains at the moment so...
You will need to learn and understanding the following for your task
Save the data using a file (json or csv up to you), or mysql if you want to further the project. See tutorials for any of this
Learn how $_POST, isset, for, foreach etc works and what they're used for
My advice is to ignore the above and start with absolute basics. Go through w3schools maybe. You're trying to build a palace when you're struggling with lego
<?php
if(isset($_POST['submit'])) {
$guess = $_POST['guess'];
$count = isset($_POST['count']) ? $_POST['count']:0;
$count++;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guess the Word Game</title>
</head>
<body>
<div id = "header">
</div>
<div id = "word">
<?php
//create array
$words = array("aardvarks", "determine", "different", "greatness", "miserable");
$random = array_rand($words);
//choose a random word from array
$newWord = $words[$random];
$change = str_split($newWord);
//prints out array
/*foreach($change as $list) {
echo $list;
}*/
$masked = str_replace($change, '*', $change);
//prints masked array
foreach($masked as $hide) {
echo $hide;
}
?>
</div>
<div id = "guess">
<form name="guessLetter" method="POST" action=""
<p>Please input your guess below</p>
<input type="text" name="guess" id="guess"/><br />
<input type="hidden" name="count" id="count" value="<?php echo $count; ?>" />
<?php
?>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit'])) {
echo "Guess: ".$guess."<br />";
echo "Count: ".$count;
}
?>
</div>
</body>
</html>
Hi everyone
I am relatively new to PHP and in the process of creating a word guessing game.
I have created an array of words and then randomized them. Once a word has been chosen, I have split the word into an array. I have then created another array for the masked version of the word which appears on the screen.
I have been ok up to here, but I now need to use a loop to iterate through array to see if the letter guessed is actually in the word. I also want to tell the user how many times the letter appears and also update the masked version of the word, with the actual letter.
I have included my code so far and would really appreciate some help as I am stuck!!
I now need to use a loop to iterate through array to see if the letter guessed is actually in the word
$letter_is_in_word = stristr($selected_word, $guess);
// returns either false if not found, or a section of the string
// where it was found ($letter_is_in_word == true)
I also want to tell the user how many times the letter appears
$number_of_occurences = substr_count($selected_word, $guess);
... and also update the masked version of the word, with the actual letter.
// get your random word
$random = array_rand($words);
$selected_word = $words[$random];
// set up temporary array to store output letters or *
$output = array();
// split word into each letter
$letters = str_split($selected_word);
foreach($letters as $letter) {
// if the letter was guessed correctly, add it to the output array,
// otherwise add a *
$output[] = ($letter == $guess) ? $letter : '*';
}
// output the results (implode joins array values together)
echo implode($output);
Something to note here is that while you are tracking the guess count via hidden input field, you aren't tracking previous guesses. I would suggest you use a hidden input field to store previous guesses also.
At the top of your page:
$count = 0;
$guesses = array();
if(isset($_POST['guesses']))
$guesses = explode('|', $_POST['guesses']);
if(isset($_POST['submit'])) {
$guess = trim(strtolower($_POST['guess']));
if(!in_array($guess, $guesses))
$guesses[] = $guess;
$count = isset($_POST['count']) ? (int) $_POST['count'] : 0;
$count++;
}
Then further down:
<input type="hidden" name="guesses" id="guesses" value="<?=implode('|', $guesses)?>">
This allows you to track previous guesses (hidden field in this example is delimited by | characters). You'll then need to check that array when you decide which letters to * out:
foreach($letters as $letter) {
// if the current letter has already been guessed, add it to
// the output array, otherwise add a *
$output[] = in_array($letter, $guesses) ? $letter : '*';
}
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 ...
}