John Beasley
John Beasley

Reputation: 3071

PHP MySQLi display error message in JavaScript alert

Is it possible to save the PHP/MySQLi "or die" error message in a variable and display it in a JavaScript alert window?

I am not using "or die" at all in the query below; is there a way to display the error in a JavaScript alert?

Here is the code that I'm using:

 <?php
   
   $update = "UPDATE table SET column1 = '$variable1', column2 = $variable2' WHERE UID = '$idVariable'";

   $query = mysqli_query($dbc, $update); // or die usually goes here

  if($query == false)
  {
    echo ("<script language='javascript'>
             window.alert('Error saving record.')
             window.location.href='javascript:history.back()'
           </script>");
  }
  else
  {
    echo ("<script language='javascript'>
             window.alert('Updated')
             window.location.href='main.php'
           </script>");
  } 

As you see above, I run a query, and if it fails, it displays a JavaScript alert stating 'Error saving record' but not what the error is. Could be a duplicate or some other error.

I want to be able to show the exact error. Is there another way to achieve this?

I was thinking something like this might work:

 $query = mysqli_query($dbc, $update) or die($error = mysqli_error());

I try to display the variable $error in the JavaScript alert window, but it does not work.

Upvotes: 2

Views: 2221

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157892

There is no such case where you would need it.

  • In case its irrecoverable error
    • In case it's production server, just say "Error". Giving out system error message is confusing and insecure. Log errors instead and read them from there.
    • In case it's development server, you don't need no fancy alerts, but plain and direct error message. Just echo it out.
  • If it's recoverable error (such as duplicate) - then handle it. Get error, check it against list of known patterns and then show user-friendly prompt to alter entered value.

Again,

System errors are not for users!

  • Regular user have no idea what duplicate index is. They only gets confused.
  • Potential hacker shouldn't be given free info on your code internals.

So, users have nothing to do with system errors. Just say apologies.

Upvotes: 3

Related Questions