This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 3 years ago.
I am new to PHP and working on an assignment. I'm almost finished but feel like I'm beating my head against the wall with this last step.
The user chooses a survey and then answers 10 questions. After the 10th question is answered, they are redirected to the results.php page which should display their questions and answers.
I know that I need to use a foreach loop but this is my first time working with them. I've finished multiple sites to get an understanding of how they work but the examples are not helping me to understand how to make it work in my assignment.
Right now I get this when I run the file:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH), expecting end of file in C:\xampp\htdocs\sandbox\HW4\results.php on line 38
When I remove the endforeach, I'm told that $answer within the echo is undefined.
I've run out of ways to change my loop. Nothing works. Some help would be appreciated. I apologize if I include code that is not relevant to my problem.
With little understanding of PHP, I'm not quite sure what I need to include and what I don't. I'm including code from my survey.php file that includes the array session and my code from the results file that should contain my foreach loop.
Thank you for your time.
$isPostBack = filter_input(INPUT_POST, 'submitButton') !== NULL;
if ($isPostBack) {
// This is what happens if there is a postback.
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_INT);
if ($choose_survey !== NULL) {
// Check the value of $choose_survey and then set 'survey' accordingly, e.g.
// These numbers are the keys to the arrays with the list of surveys
switch ($choose_survey) {
case 0:
$_SESSION['survey'] = $survey0;
break;
case 1:
$_SESSION['survey'] = $survey1;
break;
case 2:
$_SESSION['survey'] = $survey2;
break;
default:
break;
}
$_SESSION['answers'] = array();
$_SESSION['number'] = 1;
} else {
// A survey is not selected because it was already chosen.
// get the value from the radio button.
$answer = filter_input(INPUT_POST, 'answer', FILTER_DEFAULT);
if ($answer == NULL) {
echo '<p>Please select an answer before clicking Submit.</p>';
} else {
$question_key = filter_input(INPUT_POST, 'question_key', FILTER_VALIDATE_INT);
$question = $_SESSION['survey'][$question_key];
// this will be used later to display the answers/results
$_SESSION['answers'][$question] = $answer;
unset($_SESSION['survey'][$question_key]);
// This is adding 1 to the question number unless session number is 10
if ($_SESSION['number'] == 10) { // if = to 10 then we redirect to next page.
header('Location: results.php');
} else { // If number is less than 10, we add 1
$_SESSION['number'] += 1;
}
}
}
} else {
// This is what happens if there is no postback.
}
?>
results.php file
<br /> <p>Thank you for participating in the survey!</p>
<html lang="en">
<head>
<title>Survey Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="logout.php">
<p>Here are your results</p>
<input type="submit" id="submit" value="Logout" />
</form>
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
</body>
did you loaded the session_start() on your file? If not this may not enable to save your sessions that you are setting. Also on your results.php you can change your code to:
<?php foreach($_SESSION['answers'] as $question => $answer){ ?>
<p>
<?php echo $answer."<br/>"; ?>
</p>
<?php }
?>
Hope this helps!
I am not sure, but maybe you could place <?php session_start();?> at the beginning of your results.php to make your script able to work with $_SESSION variable?
Also try to var_dump($_SESSION); as in result.php, just in case.
I surprised that nobody noticed the syntax error in the foreach.
If you want to use the endforeach style, you can change your code like this (this is called Alternative Syntax):
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer): ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
Or if you want to use PHP-way to make a foreach, you can write it like this:
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) { ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php } ?>
</section>
However, for cleaner HTML & PHP code, I suggest you to write it like this:
<section>
<?php
foreach ($_SESSION['answers'] as $answer) {
echo "<p>$answer</p>" . PHP_EOL;
}
?>
</section>
Note that I removed unused $question variable.
Related
Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).
I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query
With some if/else PHP statement, I can show or hide some divs depending on if the profile page being checked out by a user belongs to that user or not.
For instance,
$id = $_SESSION['id'];
if ($uid == $id)
{
?>
<div id="block_user"></div>
<?php }
else { ?>
<div id="block_user" style="display:none"></div>
<?php
} ?>
The issue is even if the profile I'm checking out doesn't belong to me, if I inspect the element with Google webmaster tool, and remove
style="display:none"
the div becomes visible again.
How could I prevent that?
just remove the else part
<?php
if ($uid == $id) {
?>
<div id="block_user"></div>
<?php } ?>
If you want to hide stuff for real you have to dynamically create it within the PHP code... Such as :
<php
if ($uid == $id){
echo '<div id="block_user"></div>';
}
?>
which I guess you already are doing but simply dont print it out if you dont want to show it.
instead of hiding the div, remove the div element which you don't want to show.
$id = $_SESSION['id'];
if ($uid == $id)
{
?>
<div id="block_user"></div>
<?php } ?>
I've searched and tried over a dozen suggestions from similar issues on this site, but only a little closer to resoluton.
I am starting out with HTML & PHP so this is a very simplistic couple of scripts.
I am setting up an array with math questions (to test my 9 year old son).
The first script "mathtest.php" sets up the array and sets a couple of variables in the $_session global variable and then a form submits an answer to the question to "mathtest1.php".
My $_session variables are lost when I get to "mathtest1.php".
Please help. I know I can do something with cookies, but I really want to advance in my understanding of sessions.
Here's the 2 scripts:
"mathtest.php":
<?php
session_start();
?>
<html>
<title>Math Test</title>
<head>Math Test</head>
<body>
<?php
$arrayindex = 0;
for ($L = 1; $L <= 12; $L++) {
for ($R = 12; $R >= 1; $R--) {
$setupquestions[$arrayindex] = $L.'*'.$R;
$arrayindex++;
}
}
$_session["questions"] = $setupquestions;
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form action="mathtest1.php" method="post">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
The script above works as expected, but the script below has null values for the session variables I"m trying to access and use.
"mathtest1.php":
<?php
session_start();
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$answer = $_POST['answer'];
$result = eval("return $_session[questions]$_session[randomkey];");
echo "result = ".$result."<br />";
if ($answer == $result) {
echo "Correct!!";
}
else {
echo "WRONG!!";
}
}
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
Other details:
OS X, Chrome Browser, latest version of PHP
XAMPP installation & scripts are on the same laptop as XAMPP, not on an external server.
session cookies are ON
...Trans_ID is ON
I have read & write access to the session save path.
$_SESSION should be in uppercase.
try uppercase!
http://php.net/manual/en/reserved.variables.session.php
$_SESSION
Unlike function names...
function bar(){
}
function Bar(){
}
...
Fatal error: Cannot redeclare Bar() (previously declared in C:\tmp\test.php:3) in C:\tmp\test.php on line 7
... variable names are case-sensitive in PHP:
$foo = 1;
$Foo = 2;
$FOO = 3;
var_dump($foo, $Foo, $FOO);
...
int(1)
int(2)
int(3)
This applies to predefined variables as well, including $_SESSION.
I have two dev servers, one is PHP version 5.3.1 which is on my main dev machine, and the laptop that's serving as a simulated webserver has version PHP 5.2.6 on it.
The index page that's hosted with PHP 5.2.6 version will display the page correctly. The page hosted on the PHP version 5.3.1 does not.
I'm getting an error which says:
Parse error: syntax error, unexpected '}' in C:\xampp\htdocs\Greek\index.php on line 92
I have attached the code below. (However, I have to warn you it's pretty big, and I can't find a way to simply attach the file or anything like that, so it's best that I place the whole lot in here. So sorry for that.)
I have googled around to see if something like this has happened before, but I can't seem to find anything. And I thought I'd ask here.
But any help or guidance would be most appreciated.
<?php
include_once( 'admin_dataHandler.php' );
// Lets have a handle on the data connection to the data base.
// The file must be edited so that it's pointing to the correct data base.
$dataHandler = new DataConnection();
session_start(); // This connects to the existing session
$msg = "";
if ( $_SESSION['question_id'] ){
$question_id = $_SESSION['question_id'];
}else{
$question_id = 1; /* Find first question */
}
// Debugging only...
//echo $question_id;
$answer = "";
if ( $_REQUEST['action'] ){
// an action was requested..
$action = $_REQUEST['action'];
if ( $action == "answer" ){
if ( $_REQUEST['answer'] ){
$answer = $_REQUEST['answer'];
if ( $dataHandler->checkGreekWordAnswer( $question_id , $answer ) ){
/* Check to see if the answer was correct? */
$question_id = $dataHandler->getNextGreekWordQuestion( $question_id ); /* Find next question */
$answer = "";
$msg = "correct, moving on to next question.";
// then navigate to the next word.
}else{
$msg = "Incorrect. For help hit the hint button";
}
}
}else if ( $action == "next" ) {
$qid = $question_id;
$question_id = $dataHandler->getNextGreekWordQuestion( $question_id );
if( $question_id == null ){
$msg = "There are no more questions in this quiz";
// Keep the user where they're at....
$question_id = $qid;
}
}else if ( $action == "back" ){
$question_id = $dataHandler->getPreviousGreekWordQuestion( $question_id );
//echo "Current question id is " .$question_id;
if( $question_id == null ){
//echo "Something's wrong here...";
$msg = "You're at the beggining of the quiz.";
$question_id = 1;
}
}else if ( $action == "hint" ){
$msg = $dataHandler->getHint( $question_id );
if( $msg == null ){
$msg = "There are no hints for this question. Sorry";
}
}
}
$question = $dataHandler->getGreekWordQuestion( $question_id );
$_SESSION['question_id'] = $question_id;
/** Build the HTML page that's going to be the front end of the quiz.*/
?><html>
<head>
<!-- CSS STUFF HERE....-->
<link rel="stylesheet" type="text/css" href="layout.css">
<script type="text/javascript" src="translator.js"></script>
<title>Welcome to the Greek Quiz</title>
</head>
<body>
<div id="header-block">
<img>
Welcome to the Biblical Greek Quiz
</div>
<? if ( $question_id == -1 ) { ?>
<!-- this needs to be a java scripty pop up
and this H1 section needs to be in red...-->
<h1>You win!</h1>
<? }else{ ?>
<div id="quiz-section">
<span class='question'><?php echo $question; ?></span>
<form action='index.php' method='post'>
<input type='text' size='20' name='answer' id='greekAnswer' onkeyup="trans(this.id)" value='<? echo $answer; ?>'></input>
<button type='submit' name='action' value='answer'>Send</button>
<button type='submit' name='action' value='next'>Next</button>
<button type='submit' name='action' value='back'>Back</button>
<button type='submit' name='action' value='hint'>Get a hint.</button>
</form>
</div>
<?php
} <--------------- THis is the } it's not expecting....
?>
<?php
if ( $msg != "" ){ ?>
<script language='javascript'>
alert( "<?php echo $msg; ?>" );
</script>
<?php
}
?>
</body>
</html>
I have pointed out the offending line toward the end of my code block.
One server probably doesn't like your short open tags: <?. Try replacing those with <?php.
You're mixing <?php and <? tags in your code. I believe the <? variant by default is no longer recognized by PHP 5.3.
Some of the PHP blocks in your code are started using <? instead of <?php. <? can be disabled on some servers. If you change them to <?php it will work.