显示ManyToMany查询的所有结果

时间:2014-08-04 21:50:47

标签: php mysql many-to-many

我的思绪在这个问题上已经完全消失,但我目前有很多关系设置,我正在试图弄清楚如何在php端打印数据。我知道我可以调用以下命令在phpmyadmin中显示结果:

SELECT skills. * 
FROM `skills_matches` skills_matches 
LEFT JOIN `skills` ON skills.id = skills_matches.skillid 
LEFT JOIN `users` ON users.id = skills_matches.userid 
WHERE skills_matches.userid =70 LIMIT 0 , 30

然后我有以下函数来调用该查询:

function fetchAllUserSkills($id)
{
    global $mysqli,$db_table_prefix; 
    $stmt = $mysqli->prepare('SELECT skills . * '
        . ' FROM `skills_matches` skills_matches'
        . ' LEFT JOIN `skills` ON skills.id = skills_matches.skillid'
        . ' LEFT JOIN `users` ON users.id = skills_matches.userid'
        . ' WHERE skills_matches.userid = ?'
        . ' LIMIT 0 , 30');
        $stmt->bind_param("s", $id);

    $stmt->execute();
    $stmt->bind_result($id, $skills);
    while ($stmt->fetch()){
        $row = array('id' => $id, 'skills' => $skills);
    }
    $stmt->close();
    return ($row);
}

但是,当我尝试以下语句时,结果会变成空白:

$skillDetails = fetchAllUserSkills(70);
echo $skillDetails['skill'];
echo $skillDetails; 

我在$ skillDetails上做了var_dump并获得了以下内容:

array(2) { ["id"]=> int(15) ["skills"]=> string(5) "sales" }

所以问题是:为了像在phpmyadmin中那样在php中显示该查询的所有结果,我缺少什么?

1 个答案:

答案 0 :(得分:1)

你每次都要覆盖$ row:

$row = array('id' => $id, 'skills' => $skills);

应该是

$row[] = array('id' => $id, 'skills' => $skills);

然后要显示,您将遍历返回的数据:

$skillDetails = fetchAllUserSkills(70);
foreach($skillDetails as $row) {
    echo $row['skills'];
}