I have tried to create a registration for with DB using ajax and PHP but the results is not what I am looking for. It always return the 201 status code.
here's the code I have
<script>
$(document).ready(function() {
$('#butregister').on('click', function() {
$("#butregister").attr("disabled", "disabled");
var fullname = $('#fullname').val();
var username = $('#username').val();
var password = $('#password').val();
var mobilenumber = $('#mobilenumber').val();
if(fullname!="" && username!="" && mobilenumber!="" && password !=""){
$.ajax({
url: "includes/save",
datatype: "JSON",
type: "POST",
data: {
type: 1,
fullname: fullname,
username: username,
password: password,
mobilenumber: mobilenumber
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butregister").removeAttr("disabled");
$('#register_form').find('input:text').val('');
$("#success").show();
$('#success').html('Registration successful !');
}
else if(dataResult.statusCode==201){
$("#error").show();
$('#error').html('Username already exists !');
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
here's the code for the php I created
<?php
include 'connect.php';
session_start();
if($_POST['type']==1){
$fullname=$_POST['fullname'];
$username=$_POST['username'];
$password=$_POST['password'];
$mobilenumber=$_POST['mobilenumber'];
$md5password=md5($password);
$datetime = new DateTime();
$timezone = new DateTimeZone('Asia/Manila');
$datetime->setTimezone($timezone);
$dateregistered = $datetime->format('m/d/Y g:i A');
$duplicate=mysqli_query($conn,"select * from userlists where username='$username'");
if (mysqli_num_rows($duplicate)<0)
{
$sql = "INSERT INTO `userlists`( `realname`, `contactnumber`, `username`, `md5password`, `dateregistered`)
VALUES ('$fullname','$mobilenumber','$username','$md5password','$dateregistered')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
}
else{
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
}
now, after I run it, it result is always the statusCode=>201
is there anything I can do in this one? thanks
CodePudding user response:
change your if conditon
if (mysqli_num_rows($duplicate) > 0) {
CodePudding user response:
Your insert query will only run if there are -1 or less rows returned from that select query. Which I believe will never happen. Change it to:
if (mysqli_num_rows($duplicate)<=0)
{