2012-08-31 189 views
2

我有一个数组。Foreach循环与MySQL查询

$select_crm=mysql_query("select * from party_details where subcaseid='$under_row[partyid]'"); 
$select_array=array($select_crm); 
if(mysql_num_rows($select_crm)>0) 
{ 
    foreach($select_array as $v) 
    { 
    $fetch_crm=mysql_fetch_array($v); 
    echo $fetch_crm['party_name']; 
    echo $fetch_crm['partyid'];`` 
    } 
} 

但它不能正常工作。 $select_crm有两行,但它只打印一个。

回答

0

您的代码遍历仅2上面你行明确创建有一个元素;-)

您弄丢了使用mysql_fetch_assoc阵列。查看the manual page以及您的解决方案的示例代码。 (当你在那里时,注意到红色的大红色通知;请继续阅读!)。

6

$select_array是一个只有一个元素的数组:查询结果资源。因此foreach循环将只运行一次,只打印第一个项目。

你的循环应该像每一个教程在那里:

while($fetch_crm = mysql_fetch_assoc($v)) { ... } 

注意fetch_assoc,不fetch_array。如果您不打算使用数字指数,则拨打fetch_array毫无意义。

1

就我而言,你必须这样做:

$select_crm=mysql_query("select * from party_details where subcaseid='{$under_row['partyid']}'"); 
if(mysql_num_rows($select_crm)>0) 
{ 
    while ($select_array = mysql_fetch_assoc($select_crm)) 
    { 
    echo $select_array['party_name']; 
    echo $select_array['partyid']; 
    } 
} 
1

不使用的foreach,你应该以这种方式使用,

$select_crm= mysql_query("select * from party_details where subcaseid='$under_row[partyid]'"); 
while($result = $db->fetchByAssoc($select_crm)) 
{ 
    echo $result ['party_name']; 
    echo $result ['partyid']; 
} 
0

试试这个

$result = mysql_query("your select query"); 
while($row = mysql_fetch_assoc($result)){ 
echo $row['columnNam1']; 
echo $row['ColumnName2']; 
} 
0

使用此项:

$select_crm=mysql_query("select * from party_details where subcaseid='$under_row[partyid]'"); 
while($row=mysql_fetch_assoc($select_crm)) { 

echo $row['party_name']; 

echo $row['party_id']; 

} 
1

试试这个:

<?php 
$select_crm = 
mysql_query("select * from party_details where subcaseid='$under_row[partyid]'"); 

while($select_array = mysql_fetch_assoc($select_crm)) 
{ 
    echo $select_array['party_name']; 
    echo $select_array['partyid']; 
    } 
?> 

希望这将有助于。 快乐编码!