tags:

views:

41

answers:

2

Hi,

$djs_all_num = mysql_num_rows($djs_all_db);
        while($djs_all = mysql_fetch_array( $djs_all_db )) {
        if ($djs_all_num % "2") {

With my if () statement, this should halve the amount of rows, and so in the else further on it should display the rest.

Is this correct?

+6  A: 

It doesn't halve anything. It gives the remainder with 2 as divisor. This will be 0 if even, 1 if odd. So if djs_all_num is odd, it will enter the if statement. You should write 2 instead. Using the implicit conversion from string to int is confusing and unnecessary.

Note that this does not operate per-row, since the left operand is the total row count, not the row index. To use a row index, do something like:

$row_ind = 0;
$djs_all_num = mysql_num_rows($djs_all_db);
        while($djs_all = mysql_fetch_array( $djs_all_db )) {
        if ($row_ind++ % 2) {
Matthew Flaschen
I'm never getting the else running, any idea why?
Sam
It doesn't actually halve everything, but it should "split" my rows into two groups.
Sam
@Sam, if your row count is always odd, the if will always run. If you want to alternate between rows, you need to use a row index, not the row count.
Matthew Flaschen
So...how do I do this, I thought mysql_num_rows counted the number of rows.
Sam
It does; and the row count never changes, unless you execute a new query. As I said, I think you you want a row index. See my example code above.
Matthew Flaschen
thanks, this worked :).
Sam
+1  A: 

The % operator aka Modulus (edit)determines if there was a remainder(/edit). Used quite oftenly to determine odd / even rows.

So a 1 % 2 would equal .5 1 (I think if my math is correct). 2 % 2 = 0.

Hope that helps.

EDIT: Sorry did some local testing and found out my statement was incorrect, modified to be correct.

Brad F Jacobs