问题描述:

I have two tables accounts and friend_requests, here is my code...

$q = $dbc -> prepare("SELECT * FROM friend_requests WHERE id_to = ?");

$q -> execute(array($details['id']));

$account = $q -> fetch(PDO::FETCH_ASSOC);

$result = $q -> rowCount();

if ($result < 1) {

echo '<p>You haven\'t asked or been asked to be friends with anyone yet.</p><p>This is where you can accept or deny friend requests.</p>';

}

else {

$q = $dbc -> prepare("SELECT * FROM accounts WHERE id = ?");

$q -> execute(array($account['id']));

while ($request = $q -> fetch(PDO::FETCH_ASSOC)) {

echo '<p>' . $request['username'] . ' has requested to be friends with you.</p>';

}

}

You will notice I check to see if anyone has requested to be friends with the user in the first sql statement by using a rowCount() if there is a row match I pull the ID from the first table to display that users information from account, is there a better way to do this with joins whilst using rowcount??

网友答案:
$q = $dbc -> prepare ("SELECT a.* 
FROM accounts a
INNER JOIN friend_requests fr ON (a.id = fr.id)
WHERE fr.id_to = ?");
...
if (!$q -> rowCount())
{
  echo 'No requests';
}
else 
while ($request = $q -> fetch(PDO::FETCH_ASSOC)) { /// output}
相关阅读:
Top