James Wahome
James Wahome

Reputation: 597

IF ELSE statement based on count > 1 or =1 to execute different functions MY SQL php

I have a table in MY SQL that may either have an entry in a certain column as 1 or > than 1. Basically based on the current Value of the Entry in the column I would wish to run either of two methods:

Part code:

$db->prepare("SELECT vote_count FROM tbl_voter_count WHERE voter_phone_number  = :phone ");
$sql->bindParam(":phone", $phone );
try {

    $sql->execute();

} catch(PDOException $e) {

    echo $e->getMessage();

}

$data = $sql->fetchAll(PDO::FETCH_ASSOC);
if($data){
foreach ($data as $row) {
$count = $row['vote_count'];
 if($count == 1)
 {
   //Logic 1
 }

   //Logic 2

}

Based on the above,is there a better way of aciving this with far much less code entanglement and Lines.?

Upvotes: 0

Views: 105

Answers (2)

COMMANDER CAPSLOCK
COMMANDER CAPSLOCK

Reputation: 346

try {
  $sth->execute();
  foreach($sql->fetchAll(PDO::FETCH_ASSOC) as $row) {
   if($row['vote_count'] == 1) {
     //Logic 1
   } else {
   //Logic 2
   }
  }
} catch ...

edit I'd recommend using the catch at the end of the request.

Upvotes: 1

Barmar
Barmar

Reputation: 782693

Your method is fine. You can also do:

$db->prepare("SELECT vote_count > 1 as multivote FROM tbl_voter_count WHERE voter_phone_number  = :phone ");
$sql->bindParam(":phone", $phone );
try {

    $sql->execute();

} catch(PDOException $e) {

    echo $e->getMessage();

}

while ($row = $sql->fetch(PDO::FETCH_ASSOC) {
    if ($row['multivote']) {
        //Logic 1
    } else {
        //Logic 2
    }
}

Upvotes: 1

Related Questions