以下代码将运行$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>
答案 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
支票中的内容返回try
或catch
:
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;
}