[英]Comparing value submitted by user to database, redirecting based on results
我正在嘗試構建一個網頁,允許用戶輸入代碼(僅限數字和字母)。 根據代碼是否為“贏家”,它會將它們重定向到我網站上的“贏家”頁面。 否則,它會將他們重定向到“丟失”頁面。 我是新手,但我正在努力學習!
HTML:
<h1>Break Open Your Code</h1>
<form target="_blank" action="phpfile.php" method="POST">
<input type="hidden" name="code" value="1" />
<label>Enter Your Code Here</label>
<input type="text" name="answer" />
<input onclick="window.location.href = 'results-page.html';" type="submit" value="Check your Code" />
</form>
PHP:
<?php
// Connect to your MySQL database
$dbhst = "localhost";
$dbnme = "mydatabase";
$bdusr = "myusername";
$dbpws = "mypassword";
// 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 'Congrats, you've entered a correct code';
// Do Something Else
}
} else {
echo 'Your code did not win. Please try again.';
exit;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
刪除onclick="window.location.href = 'results-page.html';"
並修改<input type="hidden" name="code" value="1" />
到<input type="hidden" name="questionID" value="1" />
HTML:
<h1>Break Open Your Code</h1>
<form target="_blank" action="phpfile.php" method="POST">
<input type="hidden" name="questionID" value="1" />
<label>Enter Your Code Here</label>
<input type="text" name="answer" />
<input type="submit" value="Check your Code" />
</form>
將 html 文件保存到 form.html
現在修改phpfile.php
添加header("Location: winner.html");
如果代碼正確
添加header("Location: losing.html");
如果代碼不正確
PHP:
<?php
// Connect to your MySQL database
$dbhst = "localhost";
$dbnme = "mydatabase";
$bdusr = "myusername";
$dbpws = "mypassword";
// 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 'Congrats, you've entered a correct code';
header("Location: winner.html");
}
} else {
// echo 'Your code did not win. Please try again.';
header("Location: losing.html");
exit;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
創建 html 獲勝者。html 和失敗者。html
獲勝者.html: Congrats, you've entered a correct code
lost.html: Your code did not win. Please try again.
Your code did not win. Please try again.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.