How to compare user input with mysql database

gtanner57
Tourist
9 0 1

Hello!

I'm trying to build a page where the user can input a code (number and letter combination) they receive in a field box. If the code matches a code from my database, I want it to display a winner message, otherwise, display a different message. 

 

Sorry, I'm new to most of these things, but I'm trying to learn! Here's what I have so far.

HTML page

<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>

 

PHP code:

 

<?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 'Your code is a winner!';
// Do Something Else

}} else {

echo 'I'm sorry you did not win, please try again';
exit;

}} catch(PDOException $e) {

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

}

?>

 

* Okay, I admit "borrowed" this code. Do you think this will work? Also, how do I host a MySQL database online. Is there a way to do this on Shopify? Do I need to pay for a host service? 

 

Greatly appreciate the guidance or advice you have 

-Garrett

 

 

 

0 Likes