Skip to main content
3 of 3
deleted 2 characters in body; edited title
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Handle data received by Ajax request and update database (prepared statement)

I have an Ajax request from a page where the user is being asked to enter their date of birth. The request URL file has the code below and works all good. However, I'll be rewriting all MySQL/MySQLi functions used on the same website and this is generally how I use prepared statements. Should I avoid using die();? Is the code below acceptable and secure at some level?

// If received the birthday of logged in user
if(isset($_REQUEST['new_dob']) && isset($_REQUEST['userId'])) {
  $newdob = $_REQUEST['new_dob'];
  $userid = $_REQUEST['userId'];

  $check_info = "SELECT date_of_birth FROM users WHERE id = ? ";
  $check_mate = $conn -> prepare($check_info);
  if ( false === $check_mate ) {
    die('prepare() failed: ' . htmlspecialchars($conn->error));
  }
  $check_mate -> bind_param("i", $userid);
  $check_exe = $check_mate -> execute();
  if ( false === $check_exe ) {
    //No dob record at all for this userid
    die('execute() failed: ' . htmlspecialchars($conn->error));

  } else {
    $check_mate -> bind_result($date_of_birth);
    $check_mate -> fetch(); 
    if ($newdob != $date_of_birth) {
        $update_flag = 1;
        $check_mate -> close();
    } else if ($newdob == $date_of_birth || $newdob == '--' || $newdob == '0000-00-00' || $newdob == false || $newdob == NULL) {
        exit;
    }
  }
  if($update_flag == 1) {
    $update_dob = "UPDATE users SET date_of_birth = ? WHERE id = ? ";
    $update_exe = $conn -> prepare($update_dob);
    if ( false === $update_exe ) { 
      die('prepare() failed: ' . htmlspecialchars($conn->error));
    }
    $update_exe -> bind_param("si", $newdob, $userid);
    $update_result = $update_exe -> execute();
    if ( false === $update_result ) {
      //No record at all for this userid
      die('execute() failed: ' . htmlspecialchars($conn->error));
    } else {
        $updated = 1;
        $update_exe -> close();
    }
  } else {
    // set dialog as completed
  }
}
Ekin
  • 125
  • 7