简体   繁体   中英

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. If there is another way other than this way, please let me know.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM