Code for check value in mysql by php and successful return will redirected to another page. Basically, I want code entered in field will check within MySQL table, if found then check status in next column and if found unused, then make it used and user will redirect to the registration page. Made changes as per suggestions, received errors on webpage.
redeem-code.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<html>
<head>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "redeem_code";
$rcode = "";
$status = "";
$errors = array();
$db = mysqli_connect($servername, $username, $password, $dbname);
// call the redeem() function if redeem_btn is clicked
if (isset($_POST['redeem_btn'])) {
$err = array();
redeem();
}
// Redeem Code
function redeem(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $rcode, $status;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$rcode = e($_POST['rcode']);
$status = e($_POST['status']);
// form validation: ensure that the form is correctly filled
if (empty($rcode)) {
array_push($errors, "Code is required");
}
// Redeem Code if there are no errors in the form
if (count($errors) == 1) {
$query = "SELECT * FROM redeem_codes WHERE rcode='$rcode' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 0) {
$code_found = mysqli_fetch_assoc($results);
if ($code_found['status'] == 'unused') {
header('location: register.php');
}else{
echo "Code not found";
header('location: index.php');
}
}
else {
echo "error";
//array_push($errors, "Invalid Code");
}
}
}
?>
</head>
<body>
<?php foreach( $err as $line ) { ?>
<div style="error"><?php echo $line; ?></div>
<?php } ?>
<div class="widget">
<h3>Redeem Code</h3>
<form method="post" action="redeem.php" role="form" class="contactForm text-left">
<div class="form-group">
<input type="text" name="rcode" class="form-control" id="rcode" placeholder="Enter code" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="text-left"><button type="submit" class="btn btn-primary btn-lg" name="redeem_btn">Redeem</button>
</div>
</form>
</div>
</body>
</html>