Jump to content

PDO Check results of function


Go to solution Solved by mac_gyver,

Recommended Posts

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

  • Solution

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.