有很多麻烦不会无用地访问我的数据库

时间:2011-04-06 00:04:22

标签: php

<?php
session_start();

include '../dbconnect_form_fields.php';

$res = mysql_query("SELECT * FROM form_fields") or die(mysql_error());

echo "<form id='list' action='form_calc.php' method='post'>
<table width='100%' border='1'>
<tr><td><select>";

while($row = mysql_fetch_assoc($res)){ 
    echo "<option value='".$row['id']."'>".$row['field']." ".$row['price']."</option>";
}
echo "</select>
</td></tr>
<tr><td><select>";

$res1 = mysql_query("SELECT * FROM form_fields") or die(mysql_error());

while($row1 = mysql_fetch_assoc($res1)){ 
    echo "<option value='".$row1['id']."'>".$row1['field']." ".$row1['price']."</option>";
}
?>

出于某种原因,当我更改那行$ res1 = mysql_query blah blah blah时,它似乎无法工作,select字段为空,没有选项。似乎我必须将$ res定义为mysql_fetch,而对于第二个选择框,第二次访问DB但使用不同的变量......

如何让$ res变量在循环中传递而不必多次访问数据库...我玩这些循环中的六个...帮助我大师!

1 个答案:

答案 0 :(得分:0)

我认为您可能需要澄清您的意图。从您的代码中,您将创建两个相同的选择元素。如果要两次输出相同的select元素,可以尝试

$res = mysql_query("SELECT * FROM form_fields") or die(mysql_error());
echo "<form id='list' action='form_calc.php' method='post'>
<table width='100%' border='1'>
<tr>
<?php for($i=0;$i<1;$i++) { //Loop twice to create a second select element ?>
    <td><select>";

    while($row = mysql_fetch_assoc($res)){ 
        echo "<option value='".$row['id']."'>".$row['field']." ".$row['price']."</option>";
    }
    echo "</select>
</td>
<?php } //End of for loop ?>
</tr>

或者,您可以只复制/粘贴相同的while循环两次而不更改任何变量

<form id='list' action='form_calc.php' method='post'>
<table width='100%' border='1'>
<tr>
    <td><select>
        <?php 
        while($row = mysql_fetch_assoc($res)){ 
            echo "<option value='".$row['id']."'>".$row['field']." ".$row['price']."</option>";
        }
        ?>
        </select>
    </td>
    <td><select>
        <?php 
        while($row = mysql_fetch_assoc($res)){ 
            echo "<option value='".$row['id']."'>".$row['field']." ".$row['price']."</option>";
        }
        ?>
        </select>
    </td>
</tr>
</table>

相关问题