Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

A R
A R
12,833 Points

Variable/Input Type issue

I'm not sure exactly what's going wrong here but trying to POST the question number isn't working. It seems like the values I'm getting when I try and post aren't integers, but I'm not sure why. Thanks in advance for any help!

<?php 
    include('inc/quiz.php');
    session_start();
     ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Math Quiz: Addition</title>
    <link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
<?php 
    if (isset($_POST['page'])){
/// yes, I know I should sanitize the input, I was just trying different things to figure this out.
        $q_num = (int)$_POST['page'];
    } else {
    $q_num = 1;
 }
$num_of_q = 10;

?>
<?php var_dump($q_num);?>
    <div class="container">
        <div id="quiz-box">
            <p class="breadcrumbs">Question #<?= $q_num?> of <?= $num_of_q?></p>
            <p class="quiz">What is <?php 
            ?> </p>
            <form action="index.php" method="POST">
                <input type="hidden" name="page" value="<?php ($q_num+1);?>" />
                <input type="submit" class="btn" name="answer" value="135" />
                <input type="submit" class="btn" name="answer" value="125" />
                <input type="submit" class="btn" name="answer" value="115" />
            </form>
        </div>
    </div>
</body>
</html>

1 Answer

nathanl
nathanl
9,458 Points

Based on the code provided, I would expect $q_num to be int(1) when the page is first loaded. After submitting the form, I would expect it to be int(0).

This is because nothing is being done with the result of ($q_num+1). If you want to use the result of this operation, then you'll need to echo it out. You can do this by changing the line with <?php ($q_num+1);?> to one of the following:

<input type="hidden" name="page" value="<?php echo ($q_num + 1); ?>" />
<input type="hidden" name="page" value="<?= ($q_num + 1) ?>" />