如何在无法插入数据库的情况下确保responseText不会返回Oracle错误

时间:2015-04-01 03:04:50

标签: javascript php ajax

所以我得到了我的网站,一堆东西通过JavaScript发送到PHP,如果一切顺利,PHP会返回一个响应,其中包含"用户创建的成功"但如果它没有那么它应该只返回,"用户无法创建"或者"用户名已经存在"但是它并没有,而是它会抛出一堆Oracle错误。反正有没有确保PHP没有发送,只发送这两个字符串中的一个?

这是我的JavaScript代码:

window.onload = function findSubmitButton() {
    var button = document.querySelector(".send_info").addEventListener("click", serverInteraction); /*Unobtrusive javascript listener, added to 
                                                                                                    create account button in html*/
}


function serverInteraction() {
  var xmlhttp;
  var inputArray;
  var finalArray = [];
  var JSONArray;
  var userId;
  if (window.XMLHttpRequest){
      xmlhttp = new XMLHttpRequest();        /* Used for IE7+,FireFox, Opera, Chrome, Safari */
  } else if (window.ActiveXObject) {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   /* Compatibility for IE6 browsers */
  } else {
      throw new Error("Your browser is not compatible with XMLHTTP");
      return false;
  }

  /* The following section validates if the required inputs have text in them and if the password fields match*/
  inputArray = document.querySelectorAll("input[type=text]")
  if (inputArray[1].value != inputArray[2].value){
      alert("Password doesn't match, please make sure your password matches")
      return false;
  }

  for(var i = 0; i < inputArray.length; i++){
      if (inputArray[i].value == ""){
          alert("Please fill out all of the fields");
          return false;
      }
        finalArray[i] = inputArray[i].value;
  }
    console.log(finalArray);
    JSONArray = JSON.stringify({finalArray: finalArray}); 
    console.log(JSONArray);

    xmlhttp.onreadystatechange=function()
      {
          if (xmlhttp.readyState==4 && xmlhttp.status==200){
            if (confirm(xmlhttp.responseText)){
                window.location = 'index.html'
            }  
          }
      }

    xmlhttp.open("POST","php/sendUserInfo.php", true);
    xmlhttp.setRequestHeader("Content-type","application/json;charset=UTF-8");
    xmlhttp.send(JSONArray);
}

这是PHP,导致问题的那个:

<?php

    $db_connection = oci_connect('User', 'password', 'localhost/database');  /*Used to establish connection between database and server*/                                                                                                         
    $finalArray = file_get_contents('php://input');                                   /*Data retrieval*/            
    $finalArray = json_decode($finalArray,true);                                      /*JSON decoding*/
    $error;                 

    $username = $finalArray['finalArray'][0];              /* These variables are the data to be sent to the database */
    $password = $finalArray['finalArray'][1];
    $email = $finalArray['finalArray'][3];
    $name = $finalArray['finalArray'][4];
    $firstLastName = $finalArray['finalArray'][5];
    $secondLastName = $finalArray['finalArray'][6];

    $sqlVariableUsuarioTable = 'CALL usuario_package.add_usuario(:username, :password)';  /* SQL statement to send */
    $sqlVariablePersonTable = 'CALL person_package.add_person(:name, :first_ln, :second_ln, :username_person)';
    $sqlVariableEmailTable = 'CALL email_package.add_email(:email)';
    $dataToInsertUsuario = oci_parse($db_connection, $sqlVariableUsuarioTable);                         /* prepares statements to be sent to database */
    $dataToInsertPerson = oci_parse($db_connection, $sqlVariablePersonTable);
    $dataToInsertEmail= oci_parse($db_connection, $sqlVariableEmailTable);


    if(!$db_connection){                                    /* checks if connection with the database works */
        exit ("Server could not connect to database");
    }

    oci_bind_by_name($dataToInsertUsuario, ':username', $username);                    /* binds variables to their string names */
    oci_bind_by_name($dataToInsertUsuario, ':password', $password);
    oci_bind_by_name($dataToInsertEmail, ':email', $email);
    oci_bind_by_name($dataToInsertPerson, ':name', $name);
    oci_bind_by_name($dataToInsertPerson, ':first_ln', $firstLastName);
    oci_bind_by_name($dataToInsertPerson, ':second_ln', $secondLastName);
    oci_bind_by_name($dataToInsertPerson, ':username_person', $username);


    $arrayOfDataToSend[0] = $dataToInsertUsuario;
    $arrayOfDataToSend[1] = $dataToInsertEmail;
    $arrayOfDataToSend[2] = $dataToInsertPerson;

    foreach ($arrayOfDataToSend as $value){
        oci_execute($value);
        if(oci_error($value)['code'] == 00001){
            oci_rollback($db_connection);
            exit ("The username or email you have entered already exists");
        } else if (oci_error() != false){
            oci_rollback($db_connection);
            exit ("An error has occured with the database");
        }

    }
    exit ("Account succesfully created");
    oci_close($db_connection);

?>

我知道可以过滤,或者在插入数据之前检查用户是否存在,无论是哪种方式,我都确定这是一个更简单的解决方案。如果有人能帮我解决这个问题,我会很感激。我真的很陌生。

1 个答案:

答案 0 :(得分:0)

您需要在php

中的代码周围使用try / catch块
foreach ($arrayOfDataToSend as $value){
    try {
        oci_execute($value);
        exit ("Account successfully created");
    } catch {
        exit ("An error has occured with the database");    
    }
}

http://php.net/manual/en/language.exceptions.php