如果绑定参数返回错误,则重定向

时间:2014-12-22 21:36:11

标签: php mysql error-handling prepared-statement

我正在尝试将我的页面重定向到另一个脚本,如果有任何错误消息将显示所有错误消息。这是我想要做的:

//Prepare statement    
$checkCode = $conn->prepare("SELECT COUNT(code) FROM subscribers WHERE code LIKE ?");

    if(!$checkCode){
         header('Location:'.$errorURL."?&notification=prepareFailed");
         die();
    }else{
         $checkCode->bind_param("s", $code);
              if(!$checkcode){
                   header('Location:'.$errorURL."?&notification=bindParamFailed");
                   die();
              }else{
                   $checkCode->execute();
                   if(!$checkCode){
                        header('Location:'.$errorURL."?&notification=executeFailed");
                        die();
                   else{
                        //store result in a variable etc.}
     }
显然宣布了{p> $conn$errorURL。先前已从数据库中检索$code

此代码会将我重定向到其网址以bindParamFailed结尾的网页,因此错误来自bind_param语句。如果我注释掉if(!$checkCode){...}部分,那就像魅力一样。

为什么不起作用?有什么想法吗?

是否还有其他(可能更智能)的方法来编写这样的自定义错误页面?

2 个答案:

答案 0 :(得分:1)

虽然$conn->prepare()语句在失败时将boolean false返回到变量$checkCode,但您在$checkCode对象上进行的其他调用将不会修改该对象。它仍然是“真实的”,因此if ($checkCode)没有意义,即使绑定/执行代码失败,也永远不会输入错误状态。

相反,您需要检查这些方法调用返回的值是否成功,而不是再次检查if ($checkCode)。我建议将其重构为if()链,每个链都有可能重定向。

//Prepare statement    
// If this fails, $checkCode will indeed be boolean false
$checkCode = $conn->prepare("SELECT COUNT(code) FROM subscribers WHERE code LIKE ?");

if(!$checkCode){
  header('Location:'.$errorURL."?&notification=prepareFailed");
  die();
}

// No need for the else because you cannot reach this code unless the previous
// block was true -- it would redirect away on error.
if (!$checkCode->bind_param("s", $code)) {
  header('Location:'.$errorURL."?&notification=bindParamFailed");
  die();
}

// Same here...
if (!$checkCode->execute()) {
  header('Location:'.$errorURL."?&notification=executeFailed");
  die();
}

// All is well, store the variable
// and perform the rest of your code...

可以稍微重构一次,只调用header()一次,并在先前的错误上设置错误字符串。

//Prepare statement    
$checkCode = $conn->prepare("SELECT COUNT(code) FROM subscribers WHERE code LIKE ?");

if(!$checkCode){
  $err = "prepareFailed";
}
// On subsequent checks, test that the $err variable is still empty
// If it isn't, that section will be skipped and you'll fall through to the
// redirection header() call.
if (empty($err)) {
  if (!$checkCode->bind_param("s", $code)) {
    $err = "bindParamFailed";
  }
}
if (empty($err)) {
  if (!$checkCode->execute()) {
    $err = "executeFailed";
  }
}

// Now, if the $err string is non-empty, redirect with the message
if (!empty($err)) {
  header('Location:'.$errorURL."?&notification=$err");
  die();
}
else {
  // All is well, store the variable
  // and perform the rest of your code...
}

答案 1 :(得分:0)

这可能是因为区分大小写的变量名称。首先你使用$ checkCode = ...(驼峰案例),然后检查是否($ checkcode)(小写)。也许小写var只是未定义...