在php中将查询错误消息显示为警报?
我有一个问题及其工作原理:在php中将查询错误消息显示为警报?,php,mysql,Php,Mysql,我有一个问题及其工作原理: $sql=mysql_query("UPDATE customers SET password='$id' WHERE c_number='$users1' "); $result = mysql_query($sql); if (mysql_error()) die('Error, You have not used our services before, so no details for you to visit and explore'); 我想要的是以
$sql=mysql_query("UPDATE customers SET password='$id' WHERE c_number='$users1' ");
$result = mysql_query($sql);
if (mysql_error()) die('Error, You have not used our services before, so no details for you to visit and explore');
我想要的是以某种警报或良好显示的形式显示此错误消息。。有什么想法吗?像这样试试
if (mysql_error()) {
echo "<script type='text/javascript'>
alert('Error, You have not used our services before, so no details for you to visit and explore');
</script>";
}
if(mysql\u error()){
回声“
警报(“错误,您以前没有使用过我们的服务,因此没有详细信息供您访问和探索”);
";
}
甚至您也可以编写脚本而不重复它(不确定,但最有效),并尽量避免使用
mysql\u*
函数,因为这些函数已被删除。相反,可以使用mysqli\u*
函数或PDO
语句您只需在die
中添加一些HTML和/或JS即可:
if (mysql_error())
die('<script type="text/javascript">
alert("Error, You have not used our services before, so no details for you to visit and explore
</script>' );
if(mysql\u error())
死('
警告(“错误,您以前没有使用过我们的服务,因此没有详细信息供您访问和探索
' );
PHP DOC for and从技术上讲,该查询永远不会返回错误,除非:
if(错误){
$response=array('error'=>'error message here');
}否则{
//如果要将数据传递回调用方,请更新此选项
$response=array();
}
标题('Content-Type:application/json');
echo json_编码($response);
出口
在客户端,您可以使用AJAX提交表单,如下所示:
$.ajax({
url:“/path/to/endpoint”,
数据:{无论如何},
成功:功能(响应){
if(response.error){
警报(响应.错误);
返回;
}
//是啊,成功了
}
});
或者,也许为了服务于较旧的浏览器,您可以只生成一个(样式化的)HTML响应。我个人不喜欢页面刷新后出现一个
alert()
对话框窗口。对不起,但是您的代码完全错了(您做了两次mysql\u查询)。
我想你是说
$sql="UPDATE customers SET password='$id' WHERE c_number='$users1' ";
$result = mysql_query($sql);
if (mysql_error()) die('Error, You have not used our services before, so no details for you to visit and explore');
引用PHP手册:*从PHP 5.5.0开始,此扩展已被弃用,将来将被删除。相反,应使用MySQLi或PDO_MySQL扩展。有关更多信息,请参阅MySQL:选择API指南和相关常见问题解答*
但无论如何,让我们让这项工作(和更安全):
这通过转义$id和$users1中所有可能的特殊字符(我怀疑其中至少有一个是用户提交的数据)来防止SQL注入
这里的关键是使用mysql_查询的结果,如果查询失败,则结果为FALSE。在这里使用“==”比较器是一种很好的做法,因为我们不希望查找0或空字符串,而只希望查找布尔值FALSE。
有关更多信息,请参阅
$sql="UPDATE customers SET password='".myqsl_escape_string($id)."' WHERE c_number='".mysql_escape_string($users1)."' ";
$result = mysql_query($sql);
if ($result===false) die('Error, You have not used our services before, so no details for you to visit and explore');