In my table ‘user_sightings’ I allow multiple entries for each user, so it looks as follows…
------------------------
ID | user_ID | postcode
1 39 ab12cd
2 39 sk91ab
3 39 ab44ix
After running my query I try to print out each postcode with the following…
echo $row["postcode"];
only this only prints out the first instance for that user, Is their a way I can get all instances for the user and dynamically set them as variables?
Query:
$sth = $conn->prepare("SELECT * FROM directory, user_sightings WHERE directory.user_active != '' AND directory.ID = :uid AND user_sightings.user_ID = :uid");
$sth->execute(array(':uid' => $UID));
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row["postcode"];
}
You need a
whileloop to fetch the rows, then you can use variable assignment in PHP to assign a variable to each user:You will need a way to uniquely identify the variables, because then the last instance of that
user_IDwill be the value of that variable I would recommend using an array. Perhaps something like:This way,
$user_39will become an array containing(ab12cd, sk91ab, ab44ix).Or you can throw all your data into an array like so:
Either of those two options would go inside your
whileloop.Clarification
If you want to call the postcode for a particular user, first put the data into a multi-dimensional array:
The postcodes will then be stored like so (following example in question):
[39]represents theuser_ID