Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

how to compare the user input and the database stored answer is correct

hi, i am trying to create a page in php where user, have to answer, if the answer is correct, then they go forward, if not they can try again, the answer are stored in database.

1 Answer

Hello karthikkn! Well.. I don't know if you understand SQL codes and how is your project at the moment, but, you will need a HTML form (with text inputs) and a PHP script (which will be used to connect to a database - Are you using MySQL?).

Create a HTML file

<form action="check-answers.php" method="POST" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="questionID" value="1" />

<label>Question:</label>
<h1>Your Question Here</h1>

<label>Answer it here!</label>
<input type="text" name="answer" />

<button type="submit">
Check It
</button>
</form>

Then you'll create a PHP file used to verify if the answer is correct

<?php

// Connect to your MySQL database

    $dbhst = "yourMySQLhost";
    $dbnme = "dataBaseName"; 
    $bdusr = "dataBaseUsername";
    $dbpws = "dataBasePassword";

// Using PDO to connect

$conn = new PDO('mysql:host='.$dbhst.';dbname='.$dbnme, $bdusr, $dbpws);

// Getting variables
$answer = $_POST['answer'];
$questionID = $_POST['questionID'];

// Comparing answers

try {

    $stmt = $conn->prepare('SELECT * FROM table_with_answers WHERE question='" . $questionID . "' and answer='". $answer . "' LIMIT 0,1');
    $stmt->execute();

    $result = $stmt->fetchAll();

    if ( count($result) ) {

    foreach($result as $row) { 

    echo 'OK, you've entered a correct answer';
    // Do Something Else

    }} else {

    echo 'ERROR: Seems like you didn't put the correct answer. Please try again';
    exit;

    }} catch(PDOException $e) {

    echo 'ERROR: ' . $e->getMessage();

    }

?>

I think this should help you!!