Jump to content

Need to count how many rows does an array variable has.. help


co.ador

Recommended Posts

I am trying to adapt a pagination script the existing script I already have.

 

The first step is to count how many rows does the query has, In this case I will have to count how many rows does the array variable below has.. How can I do it?

 

<?php foreach($arrRestaurants as $arrRestaurant) {?>

 

Is there a way I can count $arrRestaurant?

 

 

below is the tutorial pagination script way of counting the numbers of row, But since I have the array variable I think I don't have a need to count it from the query, Is there a way to count that variable numbers of row?

 

The tutorial pagination script sample.

 

<php $sql = "SELECT  COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];?>

Link to comment
Share on other sites

could I have to set it up at the foreach loop or will I have to put it at the query where arrRestaurants is coming from

 

<?php     $strSQL = sprintf(
    'SELECT

          r.restaurants_id
          ,r.restaurantname
          ,r.image
	  ,r.description
	  ,r.address
	  ,r.zip
	  ,r.state
       FROM
          restaurants r
         %s
         %s
         %s'
     ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':''
     ,empty($arrSQLFilters)?'':' WHERE '.implode(' AND ',$arrSQLFilters)  
     ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':''
    );

    // Run search query    
    $arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());

    while($arrRow = mysql_fetch_assoc($arrResult)) {
        $arrRestaurants[] = $arrRow;
    }
    
} ?>

 

see at the bottom of the script above that $arrRestaurants is populate in the while loop.

 

then after that is when the foreach loop comes in hand

 

<?php  else if (!empty($arrRestaurants)){ some code...

// foreach loop
foreach($arrRestaurants as $arrRestaurant) { some html and php code inside here...

}

?>

 

and that's where $arrRestaurants is coming from.

Link to comment
Share on other sites

Instead of mysql_fetch_assoc at the while loop at the bottom of the script above use mysql_num_rows?

 

 <?php $arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());
   
    while($arrRow = mysql_num_rows($arrResult)) {
        $arrRestaurants[] = $arrRow;
    }
    
} ?>

Link to comment
Share on other sites

Instead of mysql_fetch_assoc at the while loop at the bottom of the script above use mysql_num_rows?

 

 <?php $arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());
   
    while($arrRow = mysql_num_rows($arrResult)) {
        $arrRestaurants[] = $arrRow;
    }
    
} ?>

 

that doesn't make any sense. mysql_num_rows will return an int, not a result set... there is no need to put it in a while loop, since it will return the same int regardless of how many times you loop. Hell, that might even cause an endless loop. Not to mention that he may need the information from the result set....

Link to comment
Share on other sites

I have tried to put the count inside the query

 

<?php  $strSQL = sprintf(
    'SELECT
COUNT(
          r.restaurants_id
          ,r.restaurantname
          ,r.image
	  ,r.description
	  ,r.address
	  ,r.zip
	  ,r.state)
       FROM
          restaurants r
         %s
         %s
         %s'?>

 

 

Hell it won't work...

 

:) help..

Link to comment
Share on other sites

with pagination you'll count records within query to take advantage of the LIMIT offset.

 

very, very simple count from table:

<?php
$sql = mysql_query ("
select count(*) as `total`
from `numbers`
");
$res = mysql_fetch_array ($sql);
echo $res['total']; //$res['total'] now contains the numeric value of total counted records from query;
?>

Link to comment
Share on other sites

How can I adapt the Count close to the existing query I have, Because I have to specify the fields I want to display in the html frame. I have try just to put count(*) but then it will display undefined indext errors.... but will display the data too along with the undefine errors on top of the data.... Do I have to disable some error message?

 

How Can I adapt this

 

<?php $strSQL = sprintf(
    'SELECT

          r.restaurants_id
          ,r.restaurantname
          ,r.image
	  ,r.description
	  ,r.address
	  ,r.zip
	  ,r.state
       FROM
          restaurants r
         %s
         %s
         %s'
     ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':''
     ,empty($arrSQLFilters)?'':' WHERE '.implode(' AND ',$arrSQLFilters)  
     ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':''
    );

    // Run search query    
    $arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());

    while($arrRow = mysql_fetch_assoc($arrResult)) {
        $arrRestaurants[] = $arrRow;
    }
    
} 
?>

 

To this

 

<?php
$sql = mysql_query ("
   select count(*) as `total`
   from `numbers`
");
$res = mysql_fetch_array ($sql);
echo $res['total']; //$res['total'] now contains the numeric value of total counted records from query;
?>

 

I have to specify the fields at the SELECT statement the zip, state, address etc... and then if put the Select count(*) then it will display undefined index at line x

 

 

Link to comment
Share on other sites

to be honest, i don't have a clue what you're trying to do here.

 

please give a simple, one line explanation of what you're trying to accomplish, ie.

 

are you trying to build a pagination system?

 

you are trying to count the number of restaurants in the db and display them on the page?

 

what you need to do is simplify your query, 'cause right now it's a disaster.  and when you get a simplified version working, then - and only then - start to expand on it.  'cause right now i'm seeing all kinds of PHP functions within your query and it's quite exhausting.

Link to comment
Share on other sites

right now I am trying to get a pagination system for this

 

go here www.nyhungry.com

 

then in the zip code input put 10468 then you will see there will be 5 iterations of restaurants displaying, I want to display 6 then have a next link or pagination linking to a next page where users will be able to see six restaurants more etc...

 

This is the query used for the iteration display...

 

 

<?php $strSQL = sprintf(
    'SELECT

          r.restaurants_id
          ,r.restaurantname
          ,r.image
	  ,r.description
	  ,r.address
	  ,r.zip
	  ,r.state
       FROM
          restaurants r
         %s
         %s
         %s'
     ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':''
     ,empty($arrSQLFilters)?'':' WHERE '.implode(' AND ',$arrSQLFilters)  
     ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':''
    );

    // Run search query    
    $arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());

    while($arrRow = mysql_fetch_assoc($arrResult)) {
        $arrRestaurants[] = $arrRow;
    }
    
} 
?>?>

 

Then if you see the $arrRestaurants array variable at the bottom of the above code is then pass on to the foreach loop below..

 

<?php <div id="container4">
  <div class="wrap">
     <?php // print search query
//if(!empty($strSQL)) { 
//printf('<p>%s</p>',$strSQL);


<?php else if (!empty($arrRestaurants)){?>
  <div id="container4">
  <div class="wrap">

<?php
$i = 1;
foreach($arrRestaurants as $arrRestaurant) {

  echo "<div class=\"shoeinfo1\">
   <img src=\"images/spacer.gif\" alt=\"spacer\" class=\"spacer2\" />
      <h2 class=\"infohead\">". $arrRestaurant['restaurantname'] . "</h2>
      <div class=\"pic\"><img class=\"line\" src= ". $arrRestaurant['image'] ." alt=\"picture\" width=\"100%\" height=\"100%\" /></div>

      <h5> Rating:</h5><h4>";


	$ratingData = Rating::OutputRating($arrRestaurant['restaurantname']);
      
      if (Error::HasErrors())
      {
        echo Error::ShowErrorMessages();
        Error::ClearErrors();
      }
      else
      {
        echo $ratingData;
      }  
  echo"</h4> 
    	<h3>Description:</h3>
    	<div id=\"description\"><p>".$arrRestaurant['description']." </p></div> 
	<div class=\"suabe2\">Address:<span class=\"suabe\">".$arrRestaurant['address']."</span></div>
	<div id=\"state\">State:<span class=\"suabe\">". $arrRestaurant['state']. "</span></div>
       <h6>Zip:<span class=\"suabe\">". $arrRestaurant['zip'] . "</span></h6>
<p><a href=\"#\">More</a></p></div>

";
$i++; 
if ($i > 1 && $i % 4 == 0 ) 
{
  echo "<div class=\"clearer\"></div>";

}
}
}
?>

</div>
</div>
?>

 

that's what I want to achieve.

Link to comment
Share on other sites

nice one-liner :P  had a feeling that'd be the response.

 

anyways, let's look at what you're doing as of right now.  you're gathering ALL the results into an array to be cycled out.  best case scenario, your website is a hit and you now have 25,000 restaurants in 10468.  that's a mighty large array to be picking through.

 

pagination, used most efficiently, uses the LIMIT clause, with an offset:

 

<?php
$sql = "
select *
from `table`
limit 0,10
"; //limit 0,10 would return results starting @ the first record with a limit of 10 records to be returned;

$sql = "
select *
from `table`
limit 10,10
"; //limit 10,10 would return results starting @ the 11th record in the db (if available), with a limit of 10 records to be returned;
?>

 

and so on.

 

this is how pagination works.  except, a query would look something like this:

 

<?php
$limit = 10;
$offset = $_GET['start']; //get from URL to determine where your query is starting;

$sql = "
select *
from `table`
limit {$offset},{$limit}
"; //
?>

 

anyways, that's the jist of it .. check out this Tutorial on Pagination with PHP .. written by CrayonViolent who is a member on this board.

 

EDIT: keep in mind, the example i gave above is just for an idea on how it works.  don't expect to just plug that in and *voila*.  read the tutorial by CV, it should help you get things going.

Link to comment
Share on other sites

One of the question is can I use the same query that will display the restaurants with it's fields as the pagination query?

 

another question is

 

How can count when specific fields are being choose?

 

the query in the pagination suggest to select COUNT(*) and the query I have now SELECT specific fields to count.

 

SELECT r.blabla

r.blabla

r.etc...

 

 

again is there a way to count specific fields  as I have it in the query.

 

Or should I build a query apart for the pagination ?

Link to comment
Share on other sites

you won't need to use COUNT() in your query (unless you are counting something other than just trying to use it for pagination).  the query will always be what you make it.  what you need to draw from the db is up to you.

 

read my last post for more information.

Link to comment
Share on other sites

Let's goes step by step

 

 

I am lost

 

<?php$sql = "	select *	
                                from `table`	
                                limit 0,10"; ?>

 

you see that Select statement can I impement it as below as well. The thing is that I am using the same query to avoid having several calls to the database to the same table.

 

Is this possible?

 

<?php 
$strSQL = sprintf(
    'SELECT

          r.restaurants_id
          ,r.restaurantname
          ,r.image
	  ,r.description
	  ,r.address
	  ,r.zip
	  ,r.state

       FROM
          restaurants r
         %s
         %s
         %s
	  LIMIT 0,4'

     ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':''
     ,empty($arrSQLFilters)?'':' WHERE '.implode(' AND ',$arrSQLFilters)  
     ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':''
    );

?>

 

I have put the LIMIT clause after the FROM

Link to comment
Share on other sites

LIMIT clause must go at the end of the query.

 

your limit offset must be dynamic for pagination to work.

 

your best bet would be to read the tutorial created by CV here: http://www.phpfreaks.com/tutorial/basic-pagination

 

it doesn't make sense for me to explain everything step-by-step, taking up most of my day, when somebody has already written a very well documented pagination tutorial for you to use and learn from, and incorporate into your own script.  i would just be re-writing everything that he has written, and that wouldn't make any sense.

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.

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.