spertuit Posted June 29, 2013 Share Posted June 29, 2013 I have a simple function public function showtrips($id,$table){ $sql="SELECT * FROM $table WHERE id = :id ORDER BY id DESC"; if(!$stmt = $this->conn->prepare($sql)){ // prepare failed echo "<pre>Prepare failed:\n"; print_r($pdo->errorInfo()); echo "</pre>"; } else { if(!$stmt->execute(array(':id'=>$id))){ // execute failed echo "<pre>Execute failed:\n"; print_r($stmt->errorInfo()); echo "</pre>"; } else { while($r = $stmt->fetch(PDO::FETCH_ASSOC)){ $data[]=$r; } return $data; } } } and a for loop that calls this function foreach($obj->showtrips($id,"trips") as $value){ extract($value); echo <<<show <tr class="success"> <td>$departTime</td> <td>$departPlace</td> <td>$arriveTime</td> <td>$arrivePlace</td> <td>$numberOfPass</td> <td>$purpose</td> <td>$cargo</td> <td>$remarks</td> </tr> show; } In my foreach loop how can I first test if the return variable $data has any data in it? Link to comment https://forums.phpfreaks.com/topic/279697-pdo-check-results-of-function/ Share on other sites More sharing options...
mac_gyver Posted June 29, 2013 Share Posted June 29, 2013 other than returning an empty array that would cause the foreach(){} loop to be skipped, you cannot specifically test for any condition in the foreach() statement. you would need to assign the result from the function to a variable, then test that variable before the foreach(){} statement. the only way you could alter the execution path based on there being no data would be to have the foreach(){} loop inside a try/catch block and throw an exception inside the function. Link to comment https://forums.phpfreaks.com/topic/279697-pdo-check-results-of-function/#findComment-1438565 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.