2009-12-30 91 views
0

我已经写了一个mysql查询,并使用mysql_fetch_assoc()获取结果作为assoc数组。查询返回两个字段的列表。我通过结果数组循环遍历这个字段,并提取value.how我该显示两个字段,因为做一个简单的回声,我不工作?这是我写的代码是提前检索mysql查询

感谢。

$query = "SELECT x,y FROM table"; 
$result = mysql_query($query , $resourcelink); 
while($s= mysql_fetch_assoc($result)) 
{ 
extract($s); 
    echo $x . " - " . $y . "<br />"; 
} 

回答

0

mysql_fetch_assoc返回键值映射数组。由于您没有从数据库中检索onetwo,$一个(分别为$s['one']$s['two'])$两者并不存在。因此做这样的事情,使用您选择作为键的列。

$query = "SELECT x,y FROM table"; 
$result = mysql_query($query , $resourcelink); 
while($s= mysql_fetch_assoc($result)) 
{ 
    echo $s['x'] . " - " . $s['y'] . "<br />"; 
} 

或者,如果你想继续使用提取物(我不推荐它,它会导致一些难以追踪bug)

$query = "SELECT x,y FROM table"; 
$result = mysql_query($query , $resourcelink); 
while($s= mysql_fetch_assoc($result)) 
{ 
    extract($s); 
    echo $x . " - " . $y . "<br />"; 
} 
1

我建议不要使用提取物。这使得代码很难跟进。

我只是这样做:

$query = "SELECT x,y FROM table"; 
$result = mysql_query($query , $resourcelink); 
while($s= mysql_fetch_assoc($result)) { 
    echo $s['x'], ' - ', $s['y'], '<br/>'; 
} 
0

extract是一个不好的做法,而且你的列可能会称为x和y,而不是一个两个。

我建议使用下列内容:

echo htmlspecialchars($s['x']), ' - ', htmlspecialchars($s['y']); 
+0

我很抱歉,它应该是X和Y,而不是一个两个。 – swathi 2009-12-30 15:11:19

0

根据你的SELECT语句mysql_fetch_assoc()返回类似array('x'=>something, 'y'=>something)和提取物()的阵列将 “翻译” 说给$ x = '东西' 和$ Y = “东西”,不是一个$ $和两项。

尝试

error_reporting(E_ALL); 
$query = "SELECT x,y FROM table"; 
$result = mysql_query($query , $resourcelink) or die(mysql_error()); 
echo 'there are ', mysql_num_rows($result), " records in the result set\n"; 
while(false!==($row=mysql_fetch_array($result, MYSQL_ASSOC))) { 
    echo $row['x'], ' ', $row['y'], "\n"; 
}