0

I have am using these html, php and ajax to insert data in mysql database. And I want to display success or error messages in ajax success function using SweetAlert. The data is not getting inserted into the database but able to display the messages even by just clicking on the Submit button and my codes are as follows;

server.php

<?php
session_start();

// initializing variables
$username = "";
$motor_number    = "";
$phone_number    = "";
$errors = array(); 

// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');

// REGISTER USER
if (isset($_POST['reg_user'])) {
      // receive all input values from the form
      $username = mysqli_real_escape_string($db, $_POST['username']);
      $phone_number = mysqli_real_escape_string($db, $_POST['phone_number']);
      $locationn = mysqli_real_escape_string($db, $_POST['locationn']);
      $region = mysqli_real_escape_string($db, $_POST['region']);
      $motor_number = mysqli_real_escape_string($db, $_POST['motor_number']);
      $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
      $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

    // form validation: ensure that the form is correctly filled ...
    // by adding (array_push()) corresponding error unto $errors array
    if (empty($username)) { array_push($errors, "Username is required"); }
    if (empty($phone_number)) { array_push($errors, "Phone Number is required"); }
    if (empty($locationn)) { array_push($errors, "Location is required"); }
    if (empty($region)) { array_push($errors, "Region  is required"); }
    if (empty($motor_number)) { array_push($errors, "Motor number is required"); }
    if (empty($password_1)) { array_push($errors, "Password is required"); }
    if ($password_1 != $password_2) {array_push($errors, "The two passwords do not match");}

    // first check the database to make sure 
    // a user does not already exist with the same username and/or email
    $user_check_query = "SELECT * FROM user WHERE username='$username' OR motor_num='$motor_number' LIMIT 1";
    $result = mysqli_query($db, $user_check_query);
    $user = mysqli_fetch_assoc($result);

    if ($user) { // if user exists
      if ($user['username'] === $username) {
           array_push($errors, "Username already exists");
      }

      if ($user['motor_num'] === $motor_number) {
          array_push($errors, "Motor Number already exists");
      }
    }

    // Finally, register user if there are no errors in the form
    if (count($errors) == 0) {
        $password = md5($password_1);//encrypt the password before saving in the database

        $query = "INSERT INTO user (username, phone_num, location, region, motor_num, password) 
              VALUES('$username', '$phone_number', '$locationn', '$region', '$motor_number', '$password')";
      mysqli_query($db, $query);

    }
  }


  

and this is the jQuery code

     $(function(){
    $('#reguser').click(function(e){

        var valid = this.form.checkValidity();

        if(valid){


                var username    =   $('#username').val();
                var phone_number    =   $('#phone_number').val();
                var locationn   =   $('#locationn').val();
                var region      =   $('#region').val();
                var motor_number    =   $('#motor_number').val();
                var password_1  =   $('#password_1').val();
                var comfirm_password    = $('#comfirm_password').val();
    
                    e.preventDefault(); 

                    if(username == '' || phone_number == '' || locationn == '' || region == '' || motor_number == ''){
                swal("Oops!!", "Looks like you missed some fields. Please check and try again!", "error");}
                else{
                    $.ajax({
                    type:'post',
                    url:'server.php',
                    data: {username:username, phone_number:phone_number, locationn:locationn, region:region, motor_number:motor_number,password_1:password_1, comfirm_password:comfirm_password},

                    success:function(data){
                        swal("Success", "Data Saved Successfully", "successs");
                    },
                    error:function(xhr, thrownError, ajaxOptions){

            }
   });

}

                        
        }

        

    });     

}); ```

I would be more than grateful if some one helps me figure out the problem is. Thanks in Advance

blvck kid
  • 1
  • 1
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Aug 31 '20 at 19:49
  • ***You really shouldn't use [MD5 password hashes](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure)*** and you really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. Make sure you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Aug 31 '20 at 19:49
  • Because every AJAX call returns successfully you will actually need to send a message back to the AJAX call that says "success" or "failure" and then write the proper message to the alert function. – Jay Blanchard Aug 31 '20 at 19:51
  • You should [never use `die()`](https://stackoverflow.com/a/15320411/1011527) and use `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` with your database connection code to throw errors for all of your queries when they occur. – Jay Blanchard Aug 31 '20 at 19:53

0 Answers0