Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array with unwanted first value equal to "null"

Status
Not open for further replies.

TheDust

Programmer
Aug 12, 2002
217
US
This is strange...

I have a query that goes to MySQL and returns a resultset. I then go through that result set with a "do...while" loop. It should only run for as many rows as are returned by the query. However, in my tests, only one row is being returned (which is correct), yet the loop seems to insert an extra null value in the array before adding the values from the array. Here's my code to show you what I mean:

Code:
$query_JobServices = "SELECT * FROM jobsServices js 
LEFT JOIN services s ON s.serviceID=js.serviceID 
WHERE jobID=".$row_clientsJobs['jobID']." 
ORDER BY service";
$JobServices = mysql_query($query_JobServices, $db_cpdatabase) or die(mysql_error());
$totalRows_JobServices = mysql_num_rows($JobServices);  // this is returning CORRECTLY

$arrayJobServices = array();
do {
	array_push($arrayJobServices, $row_JobServices['service']);
} while ($row_JobServices = mysql_fetch_assoc($JobServices));

The problem here is that count($arrayJobServices) returns one more than $totalRows_JobServices. The first value in the array is an empty value. Any ideas why this is happening? I've used code similar to this before and didn't have this problem... any help you can give is MUCH appreciated!
 
My first thought is that you have a row in your database with the null value.
 
I thought that may be the problem, but wouldn't that show up as an inflated number when I check $totalRows_JobServices? The number of rows returned from the query is correct, though. Weird, right?
 
Does the "do" get executed before the first evaluation of the while?
 
It was my impression that the "do...while" loop evaluates at the same time.
 
Well, I'm not sure what the problem with that code was, but I just found a different way to code this and it worked:

Code:
							// get and display multiple services
							$query_JobServices = "SELECT * FROM jobsServices js 
							LEFT JOIN services s ON s.serviceID=js.serviceID 
							WHERE jobID=".$row_clientsJobs['jobID']." 
							ORDER BY service";
							$JobServices = mysql_query($query_JobServices, $db_cpdatabase) or die(mysql_error());
							
							$arrayJobServices = array();
							while ($row = mysql_fetch_array($JobServices, MYSQL_ASSOC)) {
								array_push($arrayJobServices, $row['service']);
							}
 
Yeah, do{} while() executes the loop contents once before the evaluating the while, so the first time through the loop row_JobServices was not set.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top