简体   繁体   English

PHP MySQLi在JavaScript警报中显示错误消息

[英]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? 是否可以在变量中保存PHP / MySQLi“或死”错误消息并将其显示在JavaScript警报窗口中?

I am not using "or die" at all in the query below; 我在下面的查询中根本没有使用“或死”; is there a way to display the error in a JavaScript alert? 有没有办法在JavaScript警报中显示错误?

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. 如上所示,我运行一个查询,如果失败,它会显示一条JavaScript警告,指出“错误保存记录”但不是错误。 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. 我尝试在JavaScript警报窗口中显示变量$ error,但它不起作用。

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. 只是说道歉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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