I have a query in my foreach loop and I feel I should not be doing this.
How would I go about improving this code(Here I select Messages):
try{
$sql="
SELECT * FROM messages
WHERE workspace_id=:project_id
ORDER BY message_created DESC
LIMIT 20
OFFSET :offset";
$stmt=$db->prepare($sql);
$stmt->bindValue(':project_id', $project_id, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$messages=$stmt->fetchAll(PDO::FETCH_ASSOC);
}catch(Exception $e){echo $e->getMessage();}
Now I need users first and last name from table users. I couldn't think of another way but putting it in a loop.
foreach($messages as $row){
echo $row['message'];
$sql= "SELECT first_name, last_name FROM users
WHERE user_id=:id
LIMIT 1";
$stmt=$db->prepare($sql);
$stmt->bindValue(':id', $row['sent_by']);
$stmt->execute();
$user=$stmt->fetch(PDO::FETCH_ASSOC);
echo $user['first_name'] . " " . substr($user['last_name'],0,1) . ".";
}
This code works just the way I want it to but it doesn't look like it is supposed to be done this way.
Can anyone help me out here
joinon thesent_bymatching theidcolumn from users. like this:LEFT JOIN users on users.id = messages.sent_by