Page 1 of 1

multiple execution of a mysql query with php

Posted: Tue Sep 14, 2004 3:04 am
by nacho_c
I have the next code

Code: Select all

$query_1 = "SELECT id, name FROM languages ORDER BY name ASC";
$result_1 = mysql_query($query_1) or die ("Error in query: $query. " .mysql_error());

for ($i = 1; $i <= 6; $i++)
&#123;
print "<tr>
<td><select name="laguage_$i">";
while ($row_1 = mysql_fetch_object($result_1))
&#123;
print "<option value="$row_1->id">$row_1->name</option>\n";
&#125;
&#125;
What I want is to print 6 times the same language selection list including values from a database.

Right now the code is executed 6 times and I get 6 selection lists, but only in the first one I get the values from the database. I think that this can be probably because the $row_1 variable name is always the same, and it can“t be. Or what?... Is there any way of changing its name for each execution?

I would appreciate some help.

Posted: Tue Sep 14, 2004 3:11 am
by kettle_drum
Put it in the for statement and add a variable to the variable name or use an array and index it with the $i variable.

Posted: Tue Sep 14, 2004 3:22 am
by nacho_c
This works! Thank you anyway!

Code: Select all

$query_1 = "SELECT id, name FROM languages ORDER BY name ASC"; 
$result_1 = mysql_query($query_1) or die ("Error in query: $query. " .mysql_error()); 

$selectoptions = "";
while ($row_1 = mysql_fetch_object($result_1))
&#123;
$selectoptions .= "<option value="$row_1->id">$row_1->name</option>\n";
&#125;
for ($i = 1; $i <= 6; $i++)
&#123;
print "<tr>
<td><select name="laguage_$i">$selectoptions</select>";
&#125;

Posted: Thu Sep 16, 2004 12:51 am
by nacho_c
Ok, now another question about the same. What I should do if I want to print the same list, but with a selected option? A selected option will be printed if the user has already inserted a value to the database through this list, otherwise it will be printed without a selection.

So then, when the user goes to edit his data, he sees what he has previously inserted and he can change it.

Posted: Thu Sep 16, 2004 1:01 am
by feyd
you add the html for pre-selecting the option by checking the value of the current option against the stored option.