简体   繁体   中英

How do I return a boolean from a function in one php file to be used to determine the message in another php file?

I have a vote.php file that contains the following function.

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;

And a db.php file that contains the following function that is executed in the vote.php file above.

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();
     }


}

I wish to know how to return a boolean value to help determine the success or error message from the vote.php file.

that is. If the number casting the vote per the code in the db.php is a repeated number, the save_vote function should return a boolean value so I can check that in the vote.php file and display a message.

I am not sure how to go about returning the boolean value to the vote.php file. As it stands regardless of the response the code in the vote.php file always execute a thank you message which should not be the case.

what and how can I return a value to the code in the vote.php file to be used to determine the message displayed?

you are already returning True when OK, False when NOK. Just avoid returning a string message in other error cases. I can see [return "There is some...]. You can instead throw an exception in case of technical error [throw new Exception('There is some...')] and handle exceptions using try/catch when you call save_vote.

to summerize:

  • Vote OK: return True
  • Vote NOK: return False
  • Internal Error: throw an exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM