0

Good day all,

I've got a code that reads the users from a database and puts them in a dropdown menu:

<?php           
mysql_connect('', '', '');
mysql_select_db ("");

$sql = "SELECT id,name FROM jos_users";
$result = mysql_query($sql);


echo "<select name='deelnemers' onchange='copyId2textinput(this);'>";
while ($row = mysql_fetch_array($result)) {


echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>

Now i've got another database called jos_comprofiler with also an ID and also a avatar (image).

I was wondering if somebody give me some advise to compare the ID's from the 2 tables and then show the picture.

So for example, if i click on a user in the dropdown, it must look if there's a ID match with the other table, and if there is, show the picture from 'avatar'.

Thank you for your help and excuse me for my bad english!

4

2 回答 2

1

查询可以是:

  SELECT `ju`.`id`, `ju`.`name`, `jcp`.`avatar`  FROM `jos_users` as `ju`
  LEFT JOIN `jos_comprofiler` as `jcp` ON (`ju`.`id` = `jcp`.`id`)

这里我们使用左连接,这意味着 jos_comprofiler 不需要为每个 jos_users 都存在。在这些情况下,“头像”字段将为 NULL。

然后你在行中有元素“头像”,它可以是 NULL 或一个值。

if($row['avatar'] != NULL) echo "<img src=\"".$row['avatar']."\">";

什么的:)祝你好运

于 2013-09-11T14:36:59.933 回答
0

会有一些方法,但我会快速展示一种。

<?php           
mysql_connect('', '', '');
mysql_select_db ("");

$sql = "SELECT u.id, name, avatar FROM jos_users AS u LEFT JOIN jos_comprofiler USING(id)";
$result = mysql_query($sql);

echo "<div id='imgContainer'></div>";

echo "<select name='deelnemers' onchange='showAvatar(this.value);'>";
$avatars = array();
while ($row = mysql_fetch_array($result)) {
    if($row['avatar']){
        $avatars[$row['id']] = $row['avatar'];
}
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";

?>
<script>
    var avatars = <?=json_encode($avatars)?>;
    //alert(avatars[5]);
    var avatarContainer = document.getElementById('imgContainer');
    function showAvatar(id) {
        if(avatars[id]===undefined) return false;
        avatarContainer.innerHTML = '<img src="/path/'+avatars[id]+'" />';
    }
</script>


这应该可以工作,对您的代码进行一些修改:img 路径等。

于 2013-09-11T14:55:46.730 回答