1

我有这个功能:

function userPicBySkill($mainPassion){
$query  = mysql_query("SELECT id, username, imagename FROM users WHERE mainpassion =    '$mainPassion' ORDER BY RAND() LIMIT 5"); 

while ($row = mysql_fetch_array($query)) { 

$uid = $row["id"];
$username = $row["username"];   
$imagename = $row["imagename"];

echo "<a href='/$username'>  <img src='image/$imagename' width='40' height='41' alt =    '$username'></a>"; 
 } 
   }

如果我分配它会起作用:

 $mainpassion = 'some skill';

我想做的是从我的表“技能”中随机选择 5 个“技能”:

+----------+-----------+
|skill_id  | skill_name|
+----------+-----------+
|        1 |   guitar  |  
|        2 |   cooking |   
|        3 |   math    |    
|        4 |   plumbing|
|        5 |   piano   |
+----------+-----------+

然后为每个技能获取 5 张用户图片。我试过这个,但它没有显示任何东西:

function findRandomSkill(){

$skill_list = mysql_query("SELECT skill_name FROM skills ORDER BY RAND() LIMIT 5");
while($row = mysql_fetch_array($skill_list)){
$skill = $row['skill_name'];
echo '<div class="userBySkillDiv">
<h5>'.$skill.'</h5>';
userPicBySkill($skill);
echo'</div>';
}
4

3 回答 3

3

最好应用连接而不是执行 25 次查询:

SELECT id, username, imagename 
FROM users 
INNER JOIN (SELECT skill_name
    FROM skills
    ORDER BY RAND() 
    LIMIT 5
) userskills ON users.mainpassion = userskills.skill_name
ORDER BY RAND()
LIMIT 5
于 2012-10-08T06:29:12.190 回答
0

“什么都不显示”是什么意思?5个技能名的列表是否被返回?

要获得 5 个随机技能,请尝试$skill_list = mysql_query("SELECT DISTINCT(skill_name) FROM skills ORDER BY RAND() LIMIT 5");

于 2012-10-08T06:23:14.247 回答
0

像这样在函数中使用不同$row的变量,这会导致问题。

function userPicBySkill($mainPassion){
$query  = mysql_query("SELECT id, username, imagename FROM users WHERE mainpassion =    '$mainPassion' ORDER BY RAND() LIMIT 5"); 

while ($row1 = mysql_fetch_array($query)) { 

$uid = $row1["id"];
$username = $row1["username"];   
$imagename = $row1["imagename"];

echo "<a href='/$username'>  <img src='image/$imagename' width='40' height='41' alt =    '$username'></a>"; 
 } 
}
于 2012-10-08T06:35:04.253 回答