Issue
I'm building a website and I'd like to limit how many users can register on it.
As you can see from the photo, I have a db in phpMyAdmin called website with two tables in it. One for the codes that I create and one for store the registered users. I'd have a normal register html form with a field for 'CODE'. I 'd like to stop the user from registering if the code doesn't exist or doesn't match the codes I have in the table. After they register I'd like the code to be deleted from the table but I can't figgure out how to do it. This is my code in HTML
<form class="login-form" method="POST" action="#">
<input type="text" name="username" required="required">
<input type="password" name ="password" required="required">
<input type="text" name="code" required="required">
<input type="submit" value="Register">
</form>
PHP
<?php
$host = "192.168.11.32:3306";
$user = "cyka";
$password = "blyat";
$db = "website";
$conn = mysqli_connect($host, $user, $password, $db);
if(isset($_POST['code'])){
$userCode = $_POST['code'];
$userUsername = $_POST['username'];
$userPassword = $_POST['password'];
$sql = "SELECT * FROM codes WHERE codice = '$userCode'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)==1){
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
if ($conn->query($sql) === TRUE) {
echo "Thank you for registering!";
} else {
echo "Errore: " . $sql . "<br>" . $conn->error;
}
header('location: main.php');
} else {
echo ("The code is not valid!");
header('location: error.php');
}
}
?>
Solution
Submit the form via an ajax request upon hitting 'register' on your form.
Example of an ajax request to a back-end file:
$('#register-form').submit( function(e){
e.preventDefault();
$.ajax({
url : '/includes/register.php',
type : "POST",
data : $('#register-form').serialize(),
success : function(data) {
if (data == 'true') {
//code if successful
} else {
// code if not successful
}
}
}
});
});
All the values in the form will be posted to back-end file.
You can access the 'code' value that they have entered like this:
$theirCode = $_POST['code'];
Get an array of all your codes in your database - You can write a simple select all function:
function getCodes() {
global $db;
try {
$stmt = $db->prepare("SELECT * FROM codes");
$stmt->execute();
return $stmt->fetchall();
} catch (Exception $e) {
echo $e->getMessage();
}
}
$myCodes = getcodes();
All that you need to do now is just loop through your array of codes and check if their code matches with a code in your array.
$match = false;
foreach($myCodes as $code){
if($theirCode == $code){
$match = true;
break;
}
}
if($match == true){
echo 'true';
} else {
echo 'false';
}
Your ajax request will be listening for true/false. Handel the outcome as you wish.
I do my explanation makes sense and is of help. Thanks
Answered By - Juan J
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.