[SOLVED] multiple execution of a mysql query with php

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
nacho_c
Forum Newbie
Posts: 11
Joined: Tue Sep 14, 2004 2:56 am

multiple execution of a mysql query with php

Post 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.
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post 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.
nacho_c
Forum Newbie
Posts: 11
Joined: Tue Sep 14, 2004 2:56 am

Post 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;
nacho_c
Forum Newbie
Posts: 11
Joined: Tue Sep 14, 2004 2:56 am

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you add the html for pre-selecting the option by checking the value of the current option against the stored option.
Post Reply