I'm working on a project at home to teach myself PHP PDO. My project is to create a basic version of twitter from scratch. But I'm stuck. What I want to do is to show a list of users (ordered by id) which I can do fine but beside that list of users I want to show whether the currently logged in user is following or not following that person so I can display a link to follow or unfollow them. From what I can see, this really is a question about arrays and foreach loops.
The relevant two tables in the database looks like this (with example data):
users:
id | username
1 | Josh
2 | Sam
3 | Jane
following:
user_id | follower_id
2 | 1
3 | 1
So for example, the currently logged in user Josh (with an id of 1) is following Sam (with an id of 2). A following database row would then say follower_id 1, user_id 2.
I've written two functions to show the id and username of all my users and another to show who the currently logged in person is following. Here they are:
function show_users(){
$sql = "select id, username from users order by id";
$stmt = $GLOBALS['db']->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
function check_follow($userid){
$sql= "SELECT DISTINCT user_id FROM following WHERE follower_id = '$userid' ";
$stmt = $GLOBALS['db']->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
This all works fine if I just want to show a list of users ordered by id.
But what I want to do is to show beside the list of users a column that shows whether you are f ollowing that person i.e. and provide a link to 'follow' or 'unfollow' them.
At the moment, the relevant part of my page looks like this:
<?php
$userid = $_SESSION['user']['id'];
$following = check_follow($userid);
$rows = show_users();
?>
<h1>Follow list</h1>
<table>
<tr>
<th>id</th>
<th>Username</th>
<th>Follow status</th>
</tr>
<?php foreach($rows as $row): ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php
if (in_array($following, $rows)){
echo "<a href='#'>unfollow</a>";
}else{
echo "<a href='#'>follow</a>"; } ?>
</td>
</tr>
<?php endforeach; ?>
</table>
Everything works fine (except for the show who I am/am not follow part), it's not showing 'follow' links for some people and 'unfollow' links for others!
I've spent hours on this. I've read up on arrays, foreach, in_array, PDO fetch statements and tutorials on outputting different data and none of it helps. It doesn't either help that most of the stuff out there is non-pdo.
SOS :)