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!
There would be some ways but I'll show fast one.
<?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>
This should work, with some modification for your code: img path, etc..
Query can be:
SELECT `ju`.`id`, `ju`.`name`, `jcp`.`avatar` FROM `jos_users` as `ju`
LEFT JOIN `jos_comprofiler` as `jcp` ON (`ju`.`id` = `jcp`.`id`)
Here we use a left join, which means the jos_comprofiler does not need to exist for every jos_users. In those cases the field 'avatar' will be NULL.
Then you have in row the element 'avatar' which can be either NULL or a value.
if($row['avatar'] != NULL) echo "<img src=\"".$row['avatar']."\">";
or something :) good luck