Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Why am I not getting anything from my fetchAll? Why, why, why?

Here's my code:

for($y=1; $y<=84; $y++)
	{
	$statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
	echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
	$statement->execute();
	$row_count = $statement->fetchColumn(); 
		
		if($row_count>1)
		{
		$results=$statement->fetchAll(PDO::FETCH_ASSOC);
		echo "something";
			foreach($results as $row) 
			{
				echo $row['TotalCellSpan'];
				if($row['TotalCellSpan']>1)
				{
					echo "right here";

Open in new window


The bottom line is that I can utilize "echo" to track where I've got some data being seen by my query, but then when I go to "fetchAll" I don't get any data. It's seemingly there, but how do I get the goodness to show up on my screen?

Here's a screen shot of my misery...

User generated image
SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I suspect this is not doing what you expect
$row_count = $statement->fetchColumn(); 

Open in new window

The above code is going to fetch the value of column 0 in the next result in the result set.

If you want to check for > 1 rows returned use rowCount()
for($y=1; $y<=84; $y++) {
  $statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
  echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
  $statement->execute();
  $row_count = $statement->fetchColumn(); 
  
  // ALTERNATIVE CHECK FOR ROW COUNT  
  if($statement->rowCount() > 1) {
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    echo "something"; 
    foreach($results as $row) {
      echo $row['TotalCellSpan'];
      if($row['TotalCellSpan']>1) {
        echo "right here";

Open in new window

Avatar of Bruce Gust

ASKER

Hey, guys!

Here's what I did:

      for($y=1; $y<=84; $y++)
      {
      $statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
      echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
      $statement->execute();
      $results=$statement->fetchAll(PDO::FETCH_ASSOC);            
             if($statement->rowCount() > 1)
             {
            
            echo "something";
            foreach($results as $row)
            {
            var_dump($row);
              echo $row['TotalCellSpan'];
                  if($row['TotalCellSpan']>1)
                  {
                        echo "right here";

No data - nothing "echoed." What else do you think it could be?
So try to see what happens with

echo "<pre>";
var_dump($results);
echo "</pre>";

Open in new window

Could be that $statement->execute(); failed.  Your script can and should test the return values from these functions, then you can know whether the function worked, or if it failed, you can display the error information.

Man page on the execute() method:
http://php.net/manual/en/pdostatement.execute.php

Examples showing how to catch these sorts of errors are shown in the PDO examples here:
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
Sidebar note... This may not be causing you a debugging cycle yet but it's fraught with danger.
 $statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
      echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
      $statement->execute();

Open in new window

The reason this is dangerous is that your echo statement looks like it is producing an accurate representation of the SELECT query, but it's actually deriving its content independently from the query.  You could change the query and you would have to remember to change the echo statement, too.  That's a risky design because it violates the DRY principle.  

Instead you might want to write the code more like this:
$sql = "SELECT * FROM gant_table WHERE DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'";
$statement = $mssql_pdo->prepare($sql);
echo "$sql<br>";
$res = $statement->execute();
if (!$res) /* DETECTED FAILURE */

Open in new window

As always, gentlemen, I so appreciate your time.

Ray, I will incorporate your suggestion in a moment, but I want to get y'all a comprehensive snapshot of everything that's going on, in case there was a mistake made previously that's affecting what I've shown you thus far.

Here's the whole page from top to bottom:

<?php
//ERROR REPORTING
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL); 
require_once('projectpageclass.php');
require_once('model_class.php');

$new_page= new ProjectPage;
$page_title="South Area Network Development Project List";
$new_date=new DateCalc;

$current_row="";

if(!isset($_GET['year']))
{
	$this_year=date("Y");
}
else
{
	$this_year=$_GET['year'];
}
$the_date=$this_year;
$the_date.="-01-01";

$year_one_calc = date('c', strtotime("$the_date - 1 year"));
$year_one=date("Y", strtotime($year_one_calc)); 

$year_two=$this_year;

$year_three_calc = date('c', strtotime("$the_date + 1 year"));
$year_three=date("Y", strtotime($year_three_calc)); 

$dayNumber = date("z") + 1; 
//echo $dayNumber;

//this code is a temporary thing in order to ensure we're grabbing from live data
//include("mssql_db_cred.php");
include("carter_pdo.php");
$mssql_pdo = new PDO('mysql:host=localhost; dbname=jimmy', 'root', ''); 
$mssql_pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if(!$mssql_pdo)
{
	echo "no connection";
}
else
{
	//echo "good to go";
}

include("gant_header.php");

$number_of_cells=1;

$statement_1 = $mssql_pdo->prepare("select DataDisplay_Row from gant_table order by DataDisplay_Row DESC LIMIT 1");
$statement_1->execute();
$results_1 = $statement_1->fetchAll(PDO::FETCH_ASSOC);

foreach($results_1 as $row_1)
{
	 $number_of_rows=$row_1['DataDisplay_Row'];
}

for($i=1; $i<=$number_of_rows; $i++)
{
$body.="<tr>";
	for($y=1; $y<=84; $y++)
	{
	$statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
	echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
	$statement->execute();
	$row_count = $statement->fetchColumn(); 
		
		if($row_count>1)
		{
			echo "yes";
			$results=$statement->fetchAll(PDO::FETCH_ASSOC);
			echo "<pre>";
			var_dump($results);
			echo "</pre>";
			foreach($results as $row) 
			{                                         
				if($row['TotalCellSpan']>1)
				{
					if($row['TotalCellSpan']>=84)
					{
						$the_colspan=84;
					}
					else
					{
						$the_colspan=$row['TotalCellSpan'];
					}
				$body.="<td style=\"background-image:";
					if($row['str_Tool']=="South Area Website (PHP)")
					{
						$body.="url(images/cell_background_green.jpg);";
					}
						elseif($row['str_Tool']=="Capital Budget Tool")
						{
							$body.="url(images/cell_background_purple.jpg);";
						}
						elseif($row['str_Tool']=="Expense Budget Tool")
						{
							$body.="url(images/cell_background_violet.jpg);";
						}
						elseif($row['str_Tool']=="Real Estate Tracker")
						{
							$body.="url(images/cell_background_blue.jpg);";
						}
						elseif($row['str_Tool']=="CARRIE")
						{
							$body.="url(images/cell_background_aqua.jpg);";
						}
						elseif($row['str_Tool']=="360 Survey")
						{
							$body.="url(images/cell_background_dark_red.jpg);";
						}
						elseif($row['str_Tool']=="Regional Budget Tools")
						{
							$body.="url(images/cell_background_grey.jpg);";
						}
						elseif($row['str_Tool']=="Dev Tools")
						{
							$body.="url(images/cell_background_black.jpg);";
						}
						elseif($row['str_Tool']=="SA Portal (MVC)")
						{
							$body.="url(images/cell_background_orange.jpg);";
						}
						elseif($row['str_Tool']=="LTE Offload Tool")
						{
							$body.="url(images/cell_background_lime.jpg);";
						}
						elseif($row['str_Tool']=="Sys Perf Exec Dashboard")
						{
							$body.="url(images/cell_background_sweet_blue.jpg);";
						}
						elseif($row['str_Tool']=="CARTN Inbuilding Mailbox")
						{
							$body.="url(images/cell_background_hot_red.jpg);";
						}
						elseif($row['str_Tool']=="Infrastructure")
						{
							$body.="url(images/cell_background_scum.jpg);";
						}
						elseif($row['str_Tool']=="Cruncher Box")
						{
							$body.="url(images/cell_background_smoke.jpg);";
						}
					else
					{
						$body.="url(images/cell_background_green.jpg)";
					}
				$body.=" background-repeat:repeat-x; font-size:10pt; color:#ffffff; padding-top:3px;\" colspan=\"";
				$body.=$the_colspan;
				$body.="\">";
				$body.=$row['DataDisplay_Row'];
				$body.="</td>";
				$i=$i+($the_colspan-1);
				$the_colspan=0;
				}
				else
				{
					$body.="<td></td>";
				}
			}
		}
		else
		{
			if($i %7 !=0)
			{
				$body.="<td>&nbsp;</td>";
			}
			else
			{
				$body.="<td class=\"right_cell\"></td>";
			}
			if($i==84)
			{
				$body.="</tr>";
			}
		}
	}	
}	
				
$body.="
	<!-- this last row is just for aesthetics so there's a little room at the bottom of the page. It also gurantees a certain with for all of the \"daily\" cells -->";
	include("spacer_single.php");
	$body.="
</table><br><br>";
		
$new_page->setBody($body);

echo $new_page->display();

?>

Open in new window


Marco - line 78-80 gave me this:

array[0] {

}

Julian - one of the things that prompted me to include the whole page was something I've struggled with in that I wasn't always able to get my select statement to increment correctly. In other words, I should be getting "echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";" a total of 1428 times ($i goes up to 17 [based on what I'm getting on line 61] and $y goes up to 84). I noticed a mistake on line 72 where I called the variable $number_of_rows instead of $row_count. $number_of_rows was already used on line 61, hence the code didn't repeat like it should've.  When I used $row_count, I got a more accurate response, as far as there being data present. But I'm still not seeing that data displayed...

Ray - standby...
Ok, brucegust. That means that your query fails and returns an empty array. But I can't guess why...
Ray, here's what I did:

$sql = "SELECT * FROM gant_table WHERE DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'";
	$statement = $mssql_pdo->prepare($sql);
	echo "$sql<br>";
	$res = $statement->execute();
	if (!$res) {
	echo "something went south";
	}	/* DETECTED FAILURE */                                          
	/*$statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
	echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
	$statement->execute();*/

Open in new window


I didn't get an error, but here's what the page looks like right now:

User generated image
Is it possible that my result isn't an array? It seems like I read somewhere the difference between fetchAll and fetch was the nature of the data being retrieved...those are vowel movements, but I'm trying to figure this out.
<?php
//ERROR REPORTING
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL); 
require_once('projectpageclass.php');
require_once('model_class.php');

$new_page= new ProjectPage;
$page_title="South Area Network Development Project List";
$new_date=new DateCalc;

$current_row="";

if(!isset($_GET['year']))
{
	$this_year=date("Y");
}
else
{
	$this_year=$_GET['year'];
}
$the_date=$this_year;
$the_date.="-01-01";

$year_one_calc = date('c', strtotime("$the_date - 1 year"));
$year_one=date("Y", strtotime($year_one_calc)); 

$year_two=$this_year;

$year_three_calc = date('c', strtotime("$the_date + 1 year"));
$year_three=date("Y", strtotime($year_three_calc)); 

$dayNumber = date("z") + 1; 
//echo $dayNumber;

//this code is a temporary thing in order to ensure we're grabbing from live data
//include("mssql_db_cred.php");
include("carter_pdo.php");
$mssql_pdo = new PDO('mysql:host=localhost; dbname=jimmy', 'root', ''); 
$mssql_pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if(!$mssql_pdo)
{
	echo "no connection";
}
else
{
	//echo "good to go";
}

include("gant_header.php");

$number_of_cells=1;

$statement_1 = $mssql_pdo->prepare("select DataDisplay_Row from gant_table order by DataDisplay_Row DESC LIMIT 1");
$statement_1->execute();
$results_1 = $statement_1->fetchAll(PDO::FETCH_ASSOC);

foreach($results_1 as $row_1)
{
	 $number_of_rows=$row_1['DataDisplay_Row'];
}

for($i=1; $i<=$number_of_rows; $i++)
{
$body.="<tr>";
	for($y=1; $y<=84; $y++)
	{
	$statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
	echo "select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'.'<br>";
	$statement->execute();
	$row_count = $statement->fetchColumn(); 
		
		if($row_count>1)
		{
			echo "yes";
			$results=$statement->fetchAll(PDO::FETCH_ASSOC);
			echo "<pre>";
			var_dump($results);
			echo "</pre>";
			foreach($results as $row) 
			{                                         
				if($row['TotalCellSpan']>1)
				{
					if($row['TotalCellSpan']>=84)
					{
						$the_colspan=84;
					}
					else
					{
						$the_colspan=$row['TotalCellSpan'];
					}
				$body.="<td style=\"background-image:";
					if($row['str_Tool']=="South Area Website (PHP)")
					{
						$body.="url(images/cell_background_green.jpg);";
					}
						elseif($row['str_Tool']=="Capital Budget Tool")
						{
							$body.="url(images/cell_background_purple.jpg);";
						}
						elseif($row['str_Tool']=="Expense Budget Tool")
						{
							$body.="url(images/cell_background_violet.jpg);";
						}
						elseif($row['str_Tool']=="Real Estate Tracker")
						{
							$body.="url(images/cell_background_blue.jpg);";
						}
						elseif($row['str_Tool']=="CARRIE")
						{
							$body.="url(images/cell_background_aqua.jpg);";
						}
						elseif($row['str_Tool']=="360 Survey")
						{
							$body.="url(images/cell_background_dark_red.jpg);";
						}
						elseif($row['str_Tool']=="Regional Budget Tools")
						{
							$body.="url(images/cell_background_grey.jpg);";
						}
						elseif($row['str_Tool']=="Dev Tools")
						{
							$body.="url(images/cell_background_black.jpg);";
						}
						elseif($row['str_Tool']=="SA Portal (MVC)")
						{
							$body.="url(images/cell_background_orange.jpg);";
						}
						elseif($row['str_Tool']=="LTE Offload Tool")
						{
							$body.="url(images/cell_background_lime.jpg);";
						}
						elseif($row['str_Tool']=="Sys Perf Exec Dashboard")
						{
							$body.="url(images/cell_background_sweet_blue.jpg);";
						}
						elseif($row['str_Tool']=="CARTN Inbuilding Mailbox")
						{
							$body.="url(images/cell_background_hot_red.jpg);";
						}
						elseif($row['str_Tool']=="Infrastructure")
						{
							$body.="url(images/cell_background_scum.jpg);";
						}
						elseif($row['str_Tool']=="Cruncher Box")
						{
							$body.="url(images/cell_background_smoke.jpg);";
						}
					else
					{
						$body.="url(images/cell_background_green.jpg)";
					}
				$body.=" background-repeat:repeat-x; font-size:10pt; color:#ffffff; padding-top:3px;\" colspan=\"";
				$body.=$the_colspan;
				$body.="\">";
				$body.=$row['DataDisplay_Row'];
				$body.="</td>";
				$i=$i+($the_colspan-1);
				$the_colspan=0;
				}
				else
				{
					$body.="<td></td>";
				}
			}
		}
		else
		{
			if($i %7 !=0)
			{
				$body.="<td>&nbsp;</td>";
			}
			else
			{
				$body.="<td class=\"right_cell\"></td>";
			}
			if($i==84)
			{
				$body.="</tr>";
			}
		}
	}	
}	
				
$body.="
	<!-- this last row is just for aesthetics so there's a little room at the bottom of the page. It also gurantees a certain with for all of the \"daily\" cells -->";
	include("spacer_single.php");
	$body.="
</table><br><br>";
		
$new_page->setBody($body);

echo $new_page->display();

?>

Open in new window

If the query fails then why did you get a "something" in your output as per your original screenshot - to get that far it would have had to get past the if statement.
Secondly, why check for the rowCount at all - simply do a fetchAll - if there are no results fetchAll will return an empty array - so if you are doing a foreach over the returned array - it will drop through if no rows returned.

Going back to your code - I am intrigued by this snippet
foreach($results_1 as $row_1) {
  $number_of_rows=$row_1['DataDisplay_Row'];
}

Open in new window

Some code to spin the CPU's wheels? Going through every result and coming out with the value of the last row?
What is it you are trying to achieve with this?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm building a GANT calendar. I've already built it using MySQL and a "procedural" rich approach to my code. Here's the way it looks in production:

User generated image
I'm converting what I did to a PDO dynamic. To answer you question about:

foreach($results_1 as $row_1) {
  $number_of_rows=$row_1['DataDisplay_Row'];
}

The way that I've got things set up is the code iterates according to a specified number of rows. The row number and the cell number determines how the data is displayed.

Having built this once, the logic is sound enough, but the frustrating part right now is why am I not seeing any data, when there is data to be retrieved and, as you say, the query doesn't appear to be failing.
Just saw your other post, Julian. I'm kicking the tires now...
Julian!

This works:

for($i=1; $i<=$number_of_rows; $i++)
{
  for($y=1; $y<=84; $y++)
  {
    $statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
    $statement->execute();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    //echo "<pre>" . print_r($results, true) . "</pre>";
      foreach($results as $row)
      {
            echo $row['str_Tool'];
      }                  
  }  
}

But now, can you show me how to implement something that allows me to determine whether or not there's any data to be retrieved? This goes back to my $row_count earlier. Because if I do this:

for($i=1; $i<=$number_of_rows; $i++)
{
  for($y=1; $y<=84; $y++)
  {
    $statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
    $statement->execute();
      $row_count = $statement->fetchColumn();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    //echo "<pre>" . print_r($results, true) . "</pre>";
      foreach($results as $row)
      {
            if($row_count>0)
            {
                  echo $row['str_Tool'];
            }
            else
            {
                  echo "no";
            }
      }                  
  }  
}

I get nothing.
Lets go back a step to this
foreach($results_1 as $row_1) {
  $number_of_rows=$row_1['DataDisplay_Row'];
}

Open in new window

If we examine this statement - your code is fetching 0 - N rows - and looping through every one of them setting a variable - each time overwriting the previous value such that $number_of_rows is set to the value in the last row.

Why are you doing this as opposed to say just fetching all the rows and iterating through them? In other words

$statement = $mssql_pdo->prepare("select * from gant_table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $res) {
//    process row here
}

Open in new window

Below is a snapshot of the way the data appears in the database:

User generated image
The events have to be positioned relative to one another and not every event occupies its own row. The DataDisplay_Row value is not the number of rows in the database. Rather, it's the number of rows that will be displayed on the screen for the user based on the way each of the event's start date overlaps (or not) with another.
Bottom line: I need the max value of the DataDisplay_Row. I trust your judgement. If there's another way to do it that doesn't eat up a lot of digital gasoline, I'm definitely open...
And I still need that if statement - cannot figure that out!

Thanks for your time!
I need the max value of the DataDisplay_Row.
Ok, except your current code does not find that - it may give the right result by accident because the last value happens to have the max value in it - but if the data changes that code will give the wrong value.

But now, can you show me how to implement something that allows me to determine whether or not there's any data to be retrieved?
This is tripping you up
$row_count = $statement->fetchColumn();

Open in new window

fetchColumn advances the record pointer so you loose the record.
This is probably why you were getting an empty return
You want to do
$row_count = $statement->rowCount();

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
We are poised on the threshold of greatness, but there's still one "piece" that's alluding me.

Here's what I've got:

 

The MaxRow thing is working perfectly, but the $row_count thing is still less than what I need. Check it out:

$statement_1 = $mssql_pdo->prepare("SELECT MAX(DataDisplay_Row) AS MaxRow FROM gant_table");
$statement_1->execute();
$results_1 = $statement_1->fetchAll(PDO::FETCH_ASSOC);

foreach($results_1 as $row_1)
{
  $number_of_rows=$row_1['MaxRow'];
}

for($i=1; $i<=$number_of_rows; $i++)
{
  for($y=1; $y<=84; $y++) 
  {
    $statement = $mssql_pdo->prepare("select * from gant_table where DataDisplay_Row='$i' AND DataDisplay_StartCell='$y'");
    $statement->execute();
	$row_count = $statement->rowCount();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    //echo "<pre>" . print_r($results, true) . "</pre>";
	foreach($results as $row) 
	{ 
		if($row_count>0)
		{
			echo "yes";
		}
		else
		{
			echo "no";
		}
		
	}			
  }  
}

Open in new window


I need to be able to do something if the $row_count is not greater than 0. Right now, it doesn't seem to register anything at all and I don't know why.

Here's what my screen looks like when I run what I've got documented above:

User generated image
How can I get my code to say "no" when there's no value?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Julian, I'm glad you included that last post because I had seen that in the PHP documentation. I was able to come up with a workaround last nite, but I've since incorporated your most recent suggestion (count($results)) and it's working great.

Ray, you're right. Perhaps it's because PDO is more particular about what constitutes a legitimate result, but in the midst of doing var_dump, I could see why the system was recording a "result," though it wasn't "data." As always, I appreciate you taking the time to explain the "why" and not just the "what."

Thanks, guys!
You are welcome.