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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create array from MySQL

Status
Not open for further replies.

dodgyone

Technical User
Joined
Jan 26, 2001
Messages
431
Location
GB
I'm trying to query a table and then place this into an array which can be used to update a drop-down form box though a JavaScript function:

// create the array for servers
$query = "SELECT name FROM server";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
$row = mysql_fetch_array($result);

$j = 1;

for ($i=0; $i<$num_results; $i++) {
echo "form.state.options[$j] = new Option(\"$row[$i]\", \"$j\");\n";
$j = $j + 1;
}

The problem is that only one record is being pulled through but there shuld be 3. However, the drop-down box provides an additional 2 spaces which are empty along with the only record that manages to get through. I can't see where I'm going wrong. Am I missing something obvious here? Thanks...

================================
&quot;Chaos, panic & disorder - my work here is done!&quot;
================================
 
You have to 'pull' each record off the stack by issuing mysql_fetch_array() inside the loop:
Code:
# OLD:/*
for ($i=0; $i<$num_results; $i++) {
echo "form.state.options[$j] = new Option(\"$row[$i]\", \"$j\");\n";
$j = $j + 1;
}*/
# NEW
while ($row = mysql_fetch_array($result)){
   # your code in here to assign or produce output
}
Also, it's a good idea to add error checking to mysql_query() like
Code:
$result = mysql_query($SQL) OR die(mysql_error());
 
I've changed my code but I can't seem to make it work:

// create the array for servers
$query = "SELECT name FROM server";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);

$j = 1;

for ($i=0; $i<$num_results; $i++) {
while ($row = mysql_fetch_array($result)){
echo "form.state.options[$j] = new Option(\"$row[$i]\", \"$j\");\n";
}
$j = $j + 1;
}

I've added the while loop? ;o/

================================
&quot;Chaos, panic & disorder - my work here is done!&quot;
================================
 
The while loop replaces the for loop. You need not use the count of rows, the while structure will repeat as long as rows are in the result set.
mysql_fetch_array() pulls one row at a time.
So, just remove the for loop.
 
Silly me, forgot to put $j = $j + 1; into the while loop. It was outside. Thanks for your help...

================================
&quot;Chaos, panic & disorder - my work here is done!&quot;
================================
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top