0

I am trying to throw an exception and catch an error then echo a number.

This is what I have so far but it returns the following PHP error which in turn makes my AJAX beforeSend request hang.

PHP CODE

<?php  

  /* Status Codes

     return 0 = Nothing to Update
     return 1 = Successful Update Query
     return 2 = Database Connection refused
     return 3 = MySQL Query Error OR Wrong URL Parameters */

  if(isset($_GET["postT_VAL"])) {

  $client_id    = $_GET["postCLIENT_ID"];
  $project_id   = $_GET["postPROJECT_ID"];
  $mainsheet_id = $_GET["postMAINSHEET_ID"];
  $field_name = $_GET["postT_ID"];
  $field_value = $_GET["postT_VAL"];

  if(!$link = mysqli_connect("intentionally_mispelled", "correct_user", "correct_pass", "correct_database")) {
    echo "2";
    exit;

  } else {
  /* Build dynamic Update Query string */
  $sql = "UPDATE tbl_mainsheet2 SET ".$field_name." = '".$field_value."' WHERE client_id = '".$client_id."' AND project_id = '".$project_id."' AND mainsheet_id = '".$mainsheet_id."'";  

  /* Execute Update Query */    
  if(!mysqli_query($link, $sql)) {

  echo "3";
  /* Close Connection */
  mysqli_close($link);

  exit;

  } else {

  /* return 0 = Nothing to Update / 1 = Successful Update Query */
  echo "".mysqli_affected_rows($link);

  /* Close Connection */
  mysqli_close($link);

  }
  }

 }

?>

How can I gracefully handle this error as I've described above?

<br />
    <b>Warning</b>:  mysqli_connect(): php_network_getaddresses: getaddrinfo failed: Name or service not known in <b>/nfs/c12/h02/mnt/220474/domains/site.com/html/autosave4/processor.php</b> on line <b>20</b><br />
    <br />
    <b>Fatal error</b>:  Uncaught exception 'mysqli_sql_exception' with message 'php_network_getaddresses: getaddrinfo failed: Name or service not known' in /nfs/c12/h02/mnt/220474/domains/nexlevel.org/html/autosave4/processor.php:20
    Stack trace:
    #0 /nfs/c12/h02/mnt/220474/domains/nexlevel.org/html/autosave4/processor.php(20): mysqli_connect('intentionally_mispelled', 'correct_username', 'correct_password', 'correct_database')
    #1 {main}
      thrown in <b>/nfs/c12/h02/mnt/220474/domains/site.com/html/autosave4/processor.php</b> on line <b>20</b><br />

Basically I just want to echo a simple number 2 but PHP interrupts my echo and outputs this error stack below.

FINAL CODE - WORKING & COMMENTED

<?php  

  /* Status Codes

     return 0 = Nothing to Update
     return 1 = Successful Update Query
     return 2 = Database Connection refused
     return 3 = MySQL Query Error OR Wrong URL Parameters */

  /* Sample URL */
  // mysite.org/autosave5/processor.php?postCLIENT_ID=111&postPROJECT_ID=222&postMAINSHEET_ID=333&postT_ID=WTRESRVD&postT_VAL=147

  /* Disable Warnings so that we can return ONLY what we want through echo. */
  mysqli_report(MYSQLI_REPORT_STRICT);

  if(isset($_GET["postT_VAL"])) {

  // Initialize Global variables.
  $client_id    = '';
  $project_id   = '';
  $mainsheet_id = '';
  $field_name   = '';
  $field_value  = '';

  /* Database Connection Check */
  try
  {
    if ($link = mysqli_connect("incorrect_domain", "correct_username", "correct_password", "correct_database"))
    {

      // Set and Escape Global variables.
      $client_id    = mysqli_real_escape_string($link, $_GET["postCLIENT_ID"]);
      $project_id   = mysqli_real_escape_string($link, $_GET["postPROJECT_ID"]);
      $mainsheet_id = mysqli_real_escape_string($link, $_GET["postMAINSHEET_ID"]);
      $field_name = mysqli_real_escape_string($link, $_GET["postT_ID"]);
      $field_value = mysqli_real_escape_string($link, $_GET["postT_VAL"]);

      /* Build dynamic Update Query string */
      $sql = "UPDATE tbl_mainsheet2 SET ".$field_name." = '".$field_value."' WHERE client_id = '".$client_id."' AND project_id = '".$project_id."' AND mainsheet_id = '".$mainsheet_id."'";  

      /* Execute Update Query */    
      if(!mysqli_query($link, $sql)) {
        /* return 3 = MySQL Query Error OR Wrong URL Parameters */
        echo "3";
        /* Close Connection */
        mysqli_close($link);
        exit;
      } else {
        /* return 0 = Nothing to Update / 1 = Successful Update Query */
        echo "".mysqli_affected_rows($link);
        /* Close Connection */
        mysqli_close($link);
     }

    } else {
      throw new Exception('2');
    }
  } catch(Exception $e) {
    /* echo $e->getMessage();
       return 2 = Database Connection refused */
    echo "2";
  }

 }

?>
suchislife
  • 4,251
  • 10
  • 47
  • 78
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Aug 03 '17 at 17:05
  • Just updated! Working code posted for all to learn from. – suchislife Aug 03 '17 at 17:40

1 Answers1

1

if you want to catch and throw exceptionm don't use this kind of if statement. Use try ... catch

try
{
  if ($db = mysqli_connect($hostname_db, $username_db, $password_db, $base))
  {
    //do something
  }
  else
  {
      throw new Exception('Unable to connect');
  }
}
catch(Exception $e)
{
  echo $e->getMessage();
}
sheplu
  • 2,937
  • 3
  • 24
  • 21
  • YOU. Have just shown it in such a way I now really understand it. Just a question. Does throw new Exception('Unable to connect'); need to say 'Unable to connect' or can it be empty? – suchislife Aug 03 '17 at 16:34
  • the text `unable to connect` can be what you want. You can set it empty, or write a string with a custom message – sheplu Aug 03 '17 at 16:35
  • Correct but it seems that what is shown is the echo not what is written inside the Exception. – suchislife Aug 03 '17 at 17:42