0
down vote
favorite
I am making a puzzle game where the user must input the solution (a string) of the level before going to the next level. I’m using a simple form, which I check to validate the answer, but I have not been able to get any form to work at all.
A couple things about the way I have it set up. Each level url is stored in the database as “chapter_location” because I don’t want the user to simply guess the next level’s url. Second, I have the answers stored in the database as “chapter_solution”.
This is the php for the page that’s supposed to display the content of each level. If I try to access a page by the location, it loads the page and automatically starts trying to validate the form, then it simply spits out an empty redirect url http://localhost/chapter.php?location=
which causes a redirect loop error in any browser. I don’t know why it would try to automatically redirect before even displaying the page. Any ideas how to fix this? I have been searching tutorials for days, trying various methods and I can’t get anything to work.
<?php
include_once('includes/connection.php');
include_once('includes/chapter.php');
include('includes/header.php');
$chapter = new Chapter;
if (isset($_GET['location'])) {
$location = $_GET['location'];
$data = $chapter->fetch_data($location);
?>
<div id ="wrapper">
<h1><?php echo $data['chapter_title']; ?></h1>
<section>
<p><?php echo $data['chapter_content']; ?></p>
</section>
</div>
<div id ="solve-form">
<form action="chapter.php" method="post" autocomplete="off">
<input type="text" name="guess" placeholder="Solution:" />
<input type="submit" value="Solve" />
</form>
</div>
<?php
// Retrieve correct answer from the database stored as chapter_solution which matches current page location
$sql = "SELECT chapter_solution FROM chapters WHERE chapter_location = '$location'";
$result = mysql_query($sql);
//Validate user's solution guess against the answer stored in chapter_solution
if (isset($_POST['guess']) !== $result){
$error = 'You did not get it right. Try again.';
} else {
// increment the current chapter_id by 1 to get the next level's url from chapter_location
$next_id = ++$data['chapter_id'];
$query = 'SELECT chapter_location FROM chapters WHERE chapter_id = "$next_id"';
$next_url = mysql_query($query);
// Redirect to the url (chapter_location) of the next level.
header('Location: chapter.php?location=' . $next_url);
}
include('includes/footer.php');
} else {
header('Location: index.php');
exit();
}
?>