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";
    		echo "</pre>";
		} else {
        		// execute failed
        		echo "<pre>Execute failed:\n";
        		echo "</pre>";
    		} else {
				while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
				return $data;

and a for loop that calls this function

	foreach($obj->showtrips($id,"trips") as $value){
  	echo <<<show
      <tr class="success">

In my foreach loop how can I first test if the return variable $data has any data in it?

Link to comment
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.

Link to comment
Share on other sites

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.

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.