My Database
DBName: users, Table Name: referrals Columns:
taken, email, inviteCode
I dont know what is the correct code to check if the value of data in taken is "1" for used and "0" for not used if i enter the invite code which is already have a value of "1" in taken column it will trigger the "Already Used Code" Message.
register.php
if(isset($_POST['Register'])){
$inviteCode = ($_POST['inviteCode']);
if (empty($_POST['inviteCode'])) {
header("Location: index.php/0");
exit();
}
$rs_check = mysqli_query("SELECT * from referrals
WHERE inviteCode='$invite_code'
AND `taken` = '0'");
$num = mysqli_num_rows($rs_check);
// Match row found with more than 0 results - the code is invalid.
if ( $num <= 0) {
$err7 = "Invite code is invalid";
} else {
$inviteCode = $_POST['inviteCode'];
}
if(empty($err7)) {
$rs_check_update = mysqli_query($conn, "UPDATE referrals SET taken='1' WHERE inviteCode='$inviteCode'");
header("Location: index.php/1");
exit;
}
}
index.php
<?php
include ('register.php');
?>
<form action="register.php" method="POST">
<div class="form-email">
<p>
<?php if(isset($_GET["result"]) && $_GET["result"]=="1") { ?>
<p>Code Success</p>
<?php } ?>
</p>
<p>
<?php if(isset($_GET["result"]) && $_GET["result"]=="2") { ?>
<p>Code Already Used</p>
<?php } ?>
</p>
<p>
<?php if(isset($_GET["result"]) && $_GET["result"]=="0") { ?>
<p>Please Input A Code</p>
<?php } ?>
</p>
<input type="text" placeholder="Invite Code" name="inviteCode" />
</div>
<div class="submit3">
<input type="submit" value="Invite" name="Register" />
</div>
</form>
and also i have a problem if the code is already changed the value of taken to "1" if i submit it twice i still got the message "Code Success"
If I were to correct register.php, I would do something like this:
if(isset($_POST['Register'])){
if(!isset($_POST['inviteCode']) || $_POST['inviteCode'] == ''){
// If inviteCode is not set or empty
header('Location: index.php/0');
} else {
// Use mysqli_real_escape_string to prevent SQL injection.
// Sending raw user input to your database is very dangerous.
// Also, you don't need to assign a variable to the same thing multiple times.
$invite_code = mysqli_real_escape_string($_POST['inviteCode']);
$rs_query = 'SELECT * FROM `referrals` WHERE `inviteCode` = "'.$invite_code.'"';
$res = mysqli_query($conn, $rs_query);
$num = mysqli_num_rows($res);
if($num <= 0){
$err7 = 'Invite code is invalid.';
// You probably want to do something -like printing it- with this error.
// Just attaching it to a variable will display nothing to the user.
} else if($num == 1){
if($res->taken == 0){
$rs_check_update = 'UPDATE `referrals` SET `taken` = 1 WHERE `inviteCode` = "'.$inviteCode.'"';
if(mysqli_query($conn,$rs_check_update)){
// If the update query is successful.
header('Location: index.php/1');
} else {
// Error handling if the update query fails.
}
} else {
// taken column in db is not 0
}
}
}
}