Getting Parse Error Unexpected " - php

I am getting an error with the following message :-
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\game.php on line 12
Here is the source code :-
<?php
$words=$_GET['words'];
$array=explode(",",$words);
$j=count($array)-1;
goto a;
a: shuffle($array);
$num=$array[0];
echo "The Number Is = $num";
echo "<br />";
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER[\'PHP_SELF\']\" "; **<--Line 12**
echo "<input type=\"text\" name=\"num\"";
echo "<input type=\"submit\" value=\"Press Me! \"";
$input=$_GET['num'];
goto b;
b: if($input==$array[0] && $array!=NULL)
{
array_pop($array);
goto a;
}
elseif($array!=NULL)
{
goto a;
}
else
break;
?>
Please don't say about the GOTO but rather on how to fix the error as I am only experimenting with it to see if it would solve the given question.

Change
echo "<form method=\"get\" action=\"$_SERVER[\'PHP_SELF\']\" ";
Into
echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
It's much more simpler for the eyes.

I'll comment on all of it.
First, to fix your syntax error (and the later HTML errors you'll have). The single-quotes in the PHP_SELF substitution don't need escaped, you need to complete your opening tags, and you need to close your form tag.
<?php
$words=$_GET['words'];
$array=explode(",",$words);
$j=count($array)-1;
goto a;
a: shuffle($array);
$num=$array[0];
echo "The Number Is = $num";
echo "<br />";
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER['PHP_SELF']\" >";
echo "<input type=\"text\" name=\"num\" />";
echo "<input type=\"submit\" value=\"Press Me! \" />";
echo "</form>";
$input=$_GET['num'];
goto b;
b: if($input==$array[0] && $array!=NULL)
{
array_pop($array);
goto a;
}
elseif($array!=NULL)
{
goto a;
}
else
break;
Now, to make it not spaghetti code and to simplify your logic:
<?php
$words=$_GET['words'];
$array=explode(",",$words);
while (sizeOf($array) > 0) {
shuffle($array);
$num = $array[0];
echo "The Number Is = $num";
echo "<br />";
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER['PHP_SELF']\" >";
echo "<input type=\"text\" name=\"num\" />";
echo "<input type=\"submit\" value=\"Press Me! \" />";
echo "</form>";
$input = $_GET['num'];
if($input === $array[0]) {
array_pop($array);
}
}
Now it's at least clear what the code does - that is, the form is provided with a comma-delimited list of numbers on the query parameter "words". The list is shuffled, and the user is asked to enter the new "first" item - effectively a random item from the list. When submitted by the user, "num" is passed. If this number is the same as the first in the list, it removes the last number. Either way, as long as the array is non-null, then loops back on itself (effectively ad infinitum, spitting out the same form for each number on the list. I'm not sure this is what you wanted, since you're not handling $_GET[num] as an array.
Assuming you actually get a form, rather than just peg your server, the script then checks if "num" is present and, if so, removes it from the numbers list.
This is where it gets interesting; on submission, the script is started again. "words" is empty, so the form asks the user to enter "". If it wasn't, the list would have been re-randomized, so even if the user dutifully entered what was asked, the script wouldn't recognize it.
This is one of the reasons we don't use GOTO; it obfuscates your code flow. What's clear in a while loop is inscrutable using GOTO.
So what I assume is supposed to be the requirement:
You're presented with a number to enter. You enter it and submit the form. The number is removed from the list, and you're asked to enter another one. Once it's empty, it would be nice if you're told that.
So, to do this in a way that makes sense, let's do this using some OOP.
I know what you're going to say: this appears to be more complex - however, I want you to note that what baking everything into a class does: it encapsulates the stuff you're doing into one place, and separates out each phase of the request into separate functions.
Additionally, comments notwithstanding, it effectively documents nonobvious and repetitive tasks, like getting items off the $_REQUEST (or $_GET) object, or getting an item from an array (if it's an array and if the item exists on it) in a way that is safe and predictable.
Lastly, it's readable. It's a bit of work to look at the contents of the while loop and work out what it does; in this class, you can tell: it checks that the array is not empty and that the submitted number is the same as the requested number; if so, it removes that number.
Additionally, rather than shuffle the list each time, we just pick each one off at random.
<?php
class RandomNumberGame {
private $startCount;
private $numberMax;
private $numbers;
private $index;
/**
Produce an array containing $count random numbers between 0 and $max
*/
public function generateRandoms($count, $max) {
$nums = array();
for ($i = 0; $i < $count; $i += 1) {
$nums[] = rand(0, $max);
}
return $nums;
}
/**
Get an item from an array if it exists; if not, or if the array doesn't exist, return null
*/
public function getIfExists($array, $item) {
if (empty($array)) return null;
if (!array_key_exists($item, $array)) return null;
return $array[$item];
}
/**
returns a random number from the list of numbers
*/
function pickRandomNumber() {
return rand(0, sizeof($this->numbers) - 1);
}
/**
Handle the request data
$request
['nums'] - list of numbers with which to populate $this->numbers
['index'] - the index of the currently-selected number
['num'] - the user's entry
If nums[index] == num, that item is removed and a new index is selected.
*/
public function processRequest($request) {
$nums = $this->getIfExists($request, 'nums');
if (empty($nums)) {
$this->numbers = $this->generateRandoms($this->startCount, $this->numberMax);
} else {
$this->numbers = explode(',', $nums);
}
$this->index = $this->getIfExists($request, 'index');
if (empty($this->index)) {
$this->index = $this->pickRandomNumber();
}
$num = $this->getIfExists($request, 'num');
if (empty($num)) return;
while (!empty($this->numbers) && $this->getCurrentNumber() === $num) {
$this->removeCurrentNumber();
}
}
/**
Removes the entry in $this->numbers pointed to by $this->index, and assigns $this->index a new random position
*/
public function removeCurrentNumber() {
// In $nums, replace 1 items at $index with [] - effectively, remove item $index from $num
array_splice($this->numbers, $this->index, 1, array());
// Pick a new random item
$this->index = $this->pickRandomNumber();
}
/**
Get the currently selected number
*/
public function getCurrentNumber() {
return $this->getIfExists($this->numbers, $this->index);
}
/**
Generate the form for output to the user
If there are no numbers left, provide a congratulation, and a link to start over
*/
public function getForm($endpoint) {
if (sizeof($this->numbers) === 0) {
return "Hey, you're done! Start over.";
}
$nums = join(',', $this->numbers);
return <<<HEREDOC
<form method="post" action="{$endpoint}">
<input type="hidden" name="nums" value="{$nums}" />
<input type="hidden" name="index" value="{$this->index}" />
<label for="num">
The number is {$this->getCurrentNumber()}<br />
Please enter the number within 10 seconds<br />
<input id="num" type="text" name="num" autofocus/>
</label>
<input type="submit" value="Press Me!" />
</form>
<!-- Optional: define some Javascript to disable the form in 10 seconds -->
HEREDOC;
}
public function RandomNumberGame($startCount = 10, $numberMax = 100) {
//Basic initialization
$this->startCount = $startCount;
$this->numberMax = $numberMax;
}
}
//Finally, the program:
$rng = new RandomNumberGame();
$rng->processRequest($_REQUEST);
echo $rng->getForm($_SERVER['PHP_SELF']);

You should wrap server variable with brackets:
echo "<form method=\"get\" action=\"{$_SERVER['PHP_SELF']}\">";

printf ("<form method=\"get\" action=\"{$_SERVER['PHP_SELF']}\" ");
Two errors. You can't escape single quotes in a double quoted string, and when you are working with an array inside a string, you need to surround it with {}.

The answer is you're putting in single quotes for the array of $_SERVER:
echo "<form method=\"get\" action=\"$_SERVER[\'PHP_SELF\']\" ";
simply use
echo "<form method=\"get\" action=\"$_SERVER[PHP_SELF]\" ";
instead. the idea of the '' inside the array is to pass the string. no need to pass it within a quotes.

You're missing closing > in three lines
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER[PHP_SELF]\">";
echo "<input type=\"text\" name=\"num\">";
echo "<input type=\"submit\" value=\"Press Me! \">";
Yours:
echo "<form method=\"get\" action=\"$_SERVER['PHP_SELF']\" ";
^-- here
echo "<input type=\"text\" name=\"num\"";
^-- here
echo "<input type=\"submit\" value=\"Press Me! \"";
^-- here
Plus, [\'PHP_SELF\'] You should not be escaping single quotes.
Use [PHP_SELF] or {$_SERVER['PHP_SELF']} wrapping the variable in curly braces.

Doesnt it need a space before the != and after
From
b: if($input==$array[0] && $array!=NULL)
to this
b: if(($input==$array[0]) && ($array != NULL))
Have wrapped it in extra brackets for good measure too

Related

form post of values in array and manage them divided by key

I dont know how to manage this situation, I'm a noob coder, I have a page that shows you all available lots where you can unload a specific item from that lot.
This is the foreach that prints out:
$lotto, $totalelotto, $data, and ask for qtyvalue to unload from $lotto (input can be also NULL)
foreach ($dataslotto as $data) {
$totalelotto = totlotto($database, $data['lotto']);
$lotto = $data["lotto"];
$data = $data["data"];
echo "<tr>";
echo "<td>".$lotto."</td>";
echo "<input type=\"hidden\" value=\"".$lotto."\" name=\"array[]\" />";
echo "<td>".$totalelotto."</td>";
echo "<input type=\"hidden\" value=\"".$totalelotto."\" name=\"array[]\" />";
echo "<td>".$data."</td>";
echo "<input type=\"hidden\" value=\"".$data."\" name=\"array[]\" />";
echo "<td><input type=\"text\" class=\"form-control\" placeholder=\"Qta.\" required name=\"qtyvalue\"></td>";
echo "</tr>";
}
I dont know how to set name="" of input fields (because the number of fields can change if there are many lots) and I dont know how to send $_POST data as array, and then foreach group of $lotto, $totalelotto, $data, $qtyvalue where is set $qtyvalue do another query.
I put it in no regular code, I know it looks bad but it's just for giving you an idea.
$_POST[''formarray];
foreach ( /* values recieved in each <tr> inside formarray where $_POST['qtyvalue'] is not empty */ ){
#EXECUTE THIS
}
Thanks for help!!
And sorry for my bad coding skills.
$_POST is an Associative/Key Value pair, it's key is whatever is set as the inputs name.
so if you wanted to send the users input username to the backend PHP script
You set the value and it's name
<input type="text" name="username" value="User123">
then to retrieve the user name you can do
print_r($_POST["username"]);
to print the value.
So you ask how do you loop over each one in $_POST, that's pretty simple you can could a foreach loop over the entire $_POST array.
foreach($_POST as $key => $value)
{
//check something has been entered for the current value we are iterating over
if($value != null)
{
print_r($key . " value is : " . $value);
}
}
this would loop over each item in the $_POST array with key being set to whatever the DOM elements name is.
Don't forget the $_POST array is just that an array, you could do
var_dump($_POST);
and see everything that was sent in the POST request.
You can use array names for your inputs. Say you have a row of your table like this:
<tr>
<td><input ... name="lotto[]"></td>
<td><input ... name="totalelotto[]"></td>
<td><input ... name="data[]"></td>
<td><input ... name="qtyvalue[]"></td>
</tr>
Then you will get arrays $_POST['lotto'], $_POST['totalelotto'] and so on, each with the same number of elements, and elements with same index belonging to one row of the table. You could then process those elements like this
foreach ($_POST['lotto'] as $i=>$lotto) {
if ($_POST['qtyvalue'][$i] > 0) {
...
}
}

PHP multi directional arrays from a grid

I'm creating a crossword page on my site, I produce a grid (form) with 8 x 8 input boxes. when I fill in the answers they are sent to a page to assess them but this is where i have the problems.
the values are sent using form method GET, so if the top line read q,w,e,r,t, , ,y then it would pass this over like this :-
submit.php?0[0]=q&0[1]=w&0[2]=e&0[3]=r&0[4]=t&0[5]=&0[6]=&0[7]=y&1[0]
But when I put the values into an array, the empty values are left out, so when printing out the array it reads as "q,w,e,r,t,y" instead of "q,w,e,r,t, , ,y"
I currently fill the array like this :-
$one = $_GET['0'];
My HTML form is:
<form action='submit.php' method='get' name='xword' id='xword1'> <?php
$array=array(
array("h","e","l","l","o","0","0","0"),
array("e","0","0","0","0","0","0","0"),
array("l","0","0","0","0","0","0","0"),
array("l","0","0","0","0","0","0","0"),
array("o","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
);
$X = 0;
while ($X < "8") {
$Y = 0;
while ($Y < "8") {
if ($array[$X][$Y] == "0") {
echo "<input type='text' id='text' name='" . $X . "[$Y]' class='blank'>";
} else {
echo "<input type='text' id='text' name='" . $X . "[$Y]' class='text'>";
}
$Y++;
}
echo "<br />";
$X++;
}
?> <input type='submit' value='Submit'>
Where am I going wrong?
I don't see the empty spaces within the array being left out.
This is the output of print_r($_GET) when I type qwer in the first four text fields and ty in the last two in the first row.
Getting the data with $one = $_GET['0']; works fine (without quotes work too), and when I implode the first row, it outputs exactly what you had expected.
echo implode(', ', $_GET[0]);
OUTPUT: q, w, e, r, , , t, y

is that anyway for array to didnt back to [0] again and countinue it in last number?

i have an array which have 2 or more value ,
here my php :
for ($c = 0; $c < $jumpack; $c++) {
$packinglist = $_POST['packinglist'][$c];
$a= mysql_query("INSERT INTO packing_list VALUES('','$packinglist','$surat[id_surat]','$surat[no_surat_jalan]')");
}
and here my html :
for($i=1;$i<=5;$i++)
{
echo"
<input class='form-control' type='text' id='jumrow' name='jumpack[]' value=''/>
";
for($i=1;$i<=20;$i++){
<input class='form-control sedang' type='text' id='packinglist_$i' name='packinglist[]'/>
}
}
so i need to loop jumpack[] and i need to loop packinglist[] too
thanks
If i understand correctly you need to know the amount of fields posted?
$jumpacks = count($_POST['jumpack']);
$packinglists = count($_POST['packinglist']);
Now $jumpacks would be 5 and $packinglists would be 20 in your example.
Edit:
(trying to understand what you mean :)
foreach($_POST['jumpack'] as $jumpackvalue) {
//this means we are going over each posted jumpack, there are 5 in your example, so on each run we get the value of the next one in $jumpackvalue.
echo $jumpackvalue.'<br>'; //to test
//you can do the same now with the packinglist inside this loop
foreach($_POST['packinglist'] as $listvalue) {
echo $listvalue.'<br>'; //to test
}
}

PHP - odd one out

I am trying to create a "find the odd word" application (given a list of words like cat, dog, bird and car, the latter is the odd one because it's not an animal).
Firstly, I retrieve and shuffle randomly five words from the DB. They are called: odd (which is the odd one), one, two, three, four (which are the other four).
Then, I produce a form (radio button) with the five words, so that users can select one of their choice:
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
shuffle($words);
foreach ($words as $word)
{
$string = $word;
echo '<html><input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br></html>';
}
In the next PHP page, I want to check if the selected word is the odd one. I can't figure out how to do it.
Any suggestions? Thanks!
Use the $_SESSION variable to handle this to find out if the odd was selected or not
Say the following code is from your Odd.php that displays the radio buttons (assuming you would handle the form element and submit button)
<?php
session_start();
$_SESSION['odd'] = $odd;
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
shuffle($words);
echo '<form method="POST" action="Next.php">';
foreach ($words as $word)
{
$string = $word;
echo '<input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br>';
}
echo '<input type="submit" /></form>';
?>
On your Next.php file use the code below to validate if the odd was selected or not
<?php
session_start();
$odd = $_SESSION['odd'];
if ($_REQUEST['odd'] == $odd) { // $_REQUEST handles both $_POST and $_GET
echo "Odd was selected";
} else {
echo "Odd was not selected";
}
?>
Hope this helps!
You need to carry the odd word to the next page somehow. There are many different ways of doing this, arguably the easiest one is by saving the odd word in a variable in your form
<input type="hidden" name="realodd" value="<?php print $odd; ?>" />
On the next page, you can then check whether the chosen word is right by comparing it to the hidden word.
if ($_POST['realodd'] == $_POST['odd']) {
print "You found the odd word.";
}
This could easily be broken by just looking at the source code. A better solution could be saving the odd word in a session cookie:
session_start();
$_SESSION['realodd'] = $odd;
And then verify on the next page almost like before
if ($_SESSION['realodd'] == $_POST['odd']) {
print "You found the odd word.";
}
session_start();
if(isset($_POST['odd'])&& isset($_SESSION['odd'])&& $_POST['odd']==$_SESSION['odd']){
exit ("You're a genius, you got the right word");
}else{
if (isset($_POST['odd'])){ echo "Sorry, try again";}
}
//sql query goes here
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
$_SESSION['odd'] = $odd;
shuffle($words);
echo '<form method="POST">';
foreach ($words as $word)
{
echo '<input type="radio" name="odd" value="$word"/>$word<br><br>';
}
echo '<input type="submit" value="Submit"/>';
echo '</form>';

PHP String that is equal to $_POST will not change later, or maybe it is something else

I've been learning PHP in my spare time, and this is one of my "Hello, World" type scripts I'm doing for practice.
This is the code below, and the default strings will not change so the code will end up looping into eternity for I have no idea why:
<?php
if (isset($_POST["pbankroll"], $_POST["pstartbet"]))
{
$bankroll = $_POST["pbankroll"];
$startBet = $_POST["pstartBet"];
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>
The form to it:
<form action="index.php" method="post">
Bankroll: <input type="text" name="pbankroll">
Start Bet: <input type="text" name="pstartbet">
<input type="submit">
</form>
I appreciate the help.
The HTML name pstartbet needs to be changed to pstartBet.
Edit to clarify:
The Start Bet input element in the HTML form has the name pstartbet with the 'B' in lowercase. When PHP checks for that value, it's looking for pstartBet with the B capitalized. One of these two names needs to be changed so the cases match.
As it is:
$startBet = $_POST["pstartBet"]; // doesn't exist
This means that $startBet will be null. When cast to a number by the mathematical operations this will result in 0 - so the value of $bankroll will never change, and the loop will continue forever.
First, you'll have to convert the incoming values to integer before using them in numerical operations:
$bankroll = intval($_POST["pbankroll"]);
$startBet = intval($_POST["pstartBet"]);
Or if they are float values use:
$bankroll = floatval($_POST["pbankroll"]);
$startBet = floatval($_POST["pstartBet"]);
Beside from this, the code can of course run forever. This is because of the pseudo randum numbers that are being used. If over a long time there are more 1's then 0's generated by mat_rand() then the code will run forever
Consider that truly random numbers cannot be generated by a computer. Apparently mt_rand generates a pseudo-random number in such a way that it's causing an infinite loop.
I would recommend setting the variables outside of the if clause & setting a default of '' which basically means 'empty' & then having the if check if those two variables are empty or not.
<?php
$bankroll = array_key_exists("pbankroll", $_POST) ? intval($_POST["pbankroll"]) : '';
$startBet = array_key_exists("pstartbet", $_POST) ? intval($_POST["pstartbet"]) : '';
if (!empty($bankroll) && !empty($startBet))
{
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>

Categories