我有一个vote.php文件,其中包含以下函数。
switch ($ussdRequest->Message) {
case '1':
$db = new DB();
// save_vote will check to see if the person has already voted
$phone_number = $ussdRequest->Mobile;
//Return the array number for the selected vote to be used when updated votes
$items2 = array('1' => 'Origin Beer', '2' => 'Club Beer', '3' => 'Star Beer', '4' => 'Guinness', '5' => 'Gulder');
$voted_for = array_search($ussdRequest->ClientState, $items2) ;
$response = $db->save_vote($phone_number, $voted_for);
//echo $response;
//Display Success message after vote saved.
$ussdResponse->Message =
'Thank you. You have successfully voted for '
. $ussdRequest->ClientState . ' as your preferred Product of the Year.';
break;
case '2':
$ussdResponse->Message = 'Vote cancelled.';
break;
default:
$ussdResponse->Message = 'Invalid selection';
break;
}
$ussdResponse->Type = "Release";
break;
还有一个db.php文件,它包含在上面的vote.php文件中执行的以下函数。
function save_vote($phone_number, $voted_for) {
// Just the digits, please
$phone_number = intval(preg_replace('/\D/', '', $phone_number));
// Check to see if person has already voted
//$stmt = $this->db->prepare("SELECT COUNT(*) FROM voters WHERE phone_number=?");
//$stmt->bindValue(1, $phone_number, PDO::PARAM_INT);
//$stmt->execute();
//Try catch exception to check connection to Database.
try{
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected !";
//Check to see if person has already voted
try{
$stmt = "SELECT COUNT(*) FROM voters WHERE phone_number=?";
$results = $this->db->prepare($stmt);
$results->bindParam(1, $phone_number, PDO::PARAM_INT);
//Verify execution of query
if($results->execute()){
// If number not already voted, save their vote
if ($results->fetchColumn() == 0)
{
// Save voter
$stmt2 = "INSERT INTO voters (phone_number, voted_for) VALUES (?, ?)";
$stmt2query = $this->db->prepare($stmt2);
$stmt2query->bindValue(1, $phone_number, PDO::PARAM_INT);
$stmt2query->bindValue(2, $voted_for, PDO::PARAM_INT);
$stmt2query->execute();
// Update vote count
$stmt3 = "UPDATE brands SET votes = votes + 1 WHERE id=?";
$stmt3query = $this->db->prepare($stmt3);
$stmt3query->bindValue(1,$voted_for, PDO::PARAM_INT);
$stmt3query->execute();
return true;
//'Thank you, your vote has been recorded';
}
else {
return false; //'Sorry, you can only vote once.';
}
}
else {
return "There is some problem in updating your profile. Please contact site admin";
}
}
catch (PDOException $e) {
echo $e;
die();
}
//$values = $results->fetchAll(PDO::FETCH_OBJ);
//echo $values;
}
catch (PDOException $e) {
echo $e;
die();
}
}
我想知道如何返回一个布尔值,以帮助确定来自vote.php文件的成功或错误消息。
那是。如果按照db.php中的代码投票的数字是重复的数字,则save_vote函数应该返回一个布尔值,以便我可以在vote.php文件中检查它并显示一条消息。
我不知道如何将boolean值返回到vote.php文件。无论响应如何,vote.php文件中的代码始终执行感谢信息,但不应该是这种情况。
什么以及如何将值返回到vote.php文件中的代码以用于确定显示的消息?
你已经在OK时返回True,在NOK时返回False。只是避免在其他错误情况下返回字符串消息。我可以看到[返回“有一些...]。你可以在技术错误的情况下抛出异常[抛出新的异常('有一些......')]并在你调用时使用try / catch处理异常save_vote。
总结一下: