为什么不回声显示?

时间:2013-12-29 21:53:42

标签: php mysqli

以下代码将运行$users->vote,但不会运行echo或设置Cookie。

if(isset($_POST['confirmation']) and $_POST['confirmation']== true )
{
//We add the vote
    if($users->vote($id))
{
    echo '<strong>Your vote has successfully been recorded.</strong>';
//set a 24 hr cookie
    setcookie('topsitevoste', time()+43200);
    }
}
else{

$users->vote的功能是:

public function vote ($id){

        $query  = $this->db->prepare("UPDATE users SET votes = votes + 1 WHERE ID = ?");

        $query->bindValue(1, $id);

        try{
            $query->execute();
        }catch(PDOException $e){
            die($e->getMessage());
        }
    }

我一直在摆弄这段代码2个小时无济于事,我开始认为$query可能会在跑步时造成崩溃,但我不能为我的生活找出原因。< / p>

2 个答案:

答案 0 :(得分:3)

您的vote()函数永远不会返回任何内容,因此无法返回true if()条件以评估为true。

您可以在return前面添加$query->execute();,因为它会返回一个布尔值。

此外,它必须是$users->vote($id)$users->vote会尝试在用户对象上获取属性$vote,这样也可能导致它失败。

答案 1 :(得分:1)

清理&amp;正确格式化代码可以帮助您调试。在此,您最初调用$users->vote但不是作为连接到此类$users->vote()的类的函数。如果只调用引用变量的$users->vote$users->vote()调用函数vote(),该函数是实例化为$users的较大类的一部分:

if (isset($_POST['confirmation']) and $_POST['confirmation'] == 'true') {
    //We add the vote
    if ($users->vote($id)) {
      echo '<strong>Your vote has successfully been recorded.</strong>';
      //set a 24 hr cookie
      setcookie('topsitevoste', time()+43200);
    }
}
else {

此外,$_POST['confirmation'] == 'true'实际检查了什么?您是要检查true还是true这个词?也许那应该是:

if (isset($_POST['confirmation']) and $_POST['confirmation'] == true) {

vote()做什么(由$users->vote()调用)除了运行MySQL查询之外呢?

public function vote ($id){
  $query  = $this->db->prepare("UPDATE users SET votes = votes + 1 WHERE ID = ?");
  $query->bindValue(1, $id);

  try {
    $query->execute();
  }
  catch(PDOException $e){
    die($e->getMessage());
   }
}

所以你应该像这样重构,根据true / false支票中的内容返回trycatch

public function vote ($id){
  $query  = $this->db->prepare("UPDATE users SET votes = votes + 1 WHERE ID = ?");
  $query->bindValue(1, $id);

  try {
    $query->execute();
  }
  catch(PDOException $e){
    die($e->getMessage());
    return false;
  }
  return true;
}