Php 如何显示查询结果
查询后,我尝试显示数据。我只能从“字段_1[]”接收数据。来自“field_2[]”和来自“field[]”否。如何修复它Php 如何显示查询结果,php,mysql,Php,Mysql,查询后,我尝试显示数据。我只能从“字段_1[]”接收数据。来自“field_2[]”和来自“field[]”否。如何修复它 if (!$result) { die("Query to show fields from table failed"); } $fields_num = mysql_num_rows($result); //------------------------------------------------------------------ for($
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_rows($result);
//------------------------------------------------------------------
for($i_1=0; $i_1<$fields_num; $i_1++)
{
$field_1 = mysql_fetch_assoc($result);
echo "<td>a".$field_1['index_period_1']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_assoc($result);
echo "<td>b".$field['index_period']."</td>";
}
//------------------------------------------------------------------
//------------------------------------------------------------------
for($i_2=0; $i_2<$fields_num; $i_2++)
{
$field_2 = mysql_fetch_assoc($result);
echo "<td>c".$field_2['index_period_2']."</td>";
}
您有点忽略了mysql中的
mysql\u fetch\u assoc()
和行:
while ($row = mysql_fetch_assoc($result)) {
echo $row['index_period'];
echo $row['index_period_1'];
echo $row['index_period_2'];
}
每行调用mysql\u fetch\u assoc()
一次
我不知道你为什么要这样绕桌子,但我不会审问你 这可能符合你的需要(我不愿意写这个):
$index_period=array();
$index_period_1=数组();
$index_period_2=数组();
while($row=mysql\u fetch\u assoc($result)){
$index_period[]=$row['index_period'];
$index_period_1[]=$row['index_period_1'];
$index_period_2[]=$row['index_period_2'];
}
foreach($index\u期间为$value){
呼应“a”。$value.”;
}
foreach($index\u period\u 1作为$value){
回显“b”。$value.”;
}
foreach($index\u period\u 2作为$value){
回显“c”。$value.”;
}
完成第一个for循环后,您已经遍历了整个结果集。因此,当您输入下一个for循环时,就没有什么可迭代的了,mysql\u fetch\u assoc()
返回false。如果要重置内部数据指针,可以调用
mysql_data_seek($result, 0);
这将使您能够在下一个for循环中重新迭代结果集。我不能这样做。它必须有助于生成html表。我必须以3种方式接收$field[]、$field_1[]和$field_2[]。我的代码与您的代码有何不同?我刚刚省略了
标记。@安德鲁:这就是mysql\u fetch\u assoc
的工作原理。您可以通过行而不是字段循环浏览结果。您可以创建3个数组(或一个2D数组),然后将每个字段放入各自的数组中,然后循环遍历这些数组并创建表格。@Blender:似乎他试图循环遍历每个字段,而不是每行。@Rocket:所以他试图循环遍历列?“我来看看我能帮什么忙。”安德鲁:没问题。尽管您可能会查看@Blender和@Rocket提到的信息,但只要掌握使用mysql\u fetch\u assoc
迭代结果集的概念即可。德国劳埃德船级社
$index_period = array();
$index_period_1 = array();
$index_period_2 = array();
while ($row = mysql_fetch_assoc($result)) {
$index_period[] = $row['index_period'];
$index_period_1[] = $row['index_period_1'];
$index_period_2[] = $row['index_period_2'];
}
foreach ($index_period as $value) {
echo "<td>a" . $value . "</td>";
}
foreach ($index_period_1 as $value) {
echo "<td>b" . $value . "</td>";
}
foreach ($index_period_2 as $value) {
echo "<td>c" . $value . "</td>";
}
mysql_data_seek($result, 0);