Curretly I show profile images using session like this:
<img src="<?php if (isset($_SESSION['userimage'])){
echo $_SESSION['userimage']; }?>" />
What are the upsides and downsides of fetching them from MySQL directly like this:
<img src="<?php echo $row['userimage'] ?>"/>
Does it have any performance effect? I see that a lot programmers choose to display username from the session to greet user being logged in rather than fetching it from the DB.
I assume, you have a File Path in the Database to the Image and also need to fetch it once, to get into the Session.
If you don't need anything from the Database, at least from this User, you should store all in the Session.
If you still need to connect to the Database, and especialy fetch Data from the User Row, you should go with the second approach.
It is depended on the usecase and the costs about it. Try a little Benchmarking.
Also think about a good caching machnism. It can bring much more optimization, then this here.
Also I would have something like this:
function showUserImage($url = null) {
if (!isset($url)) {
$url = 'standarduserpic.png';
}
echo '<img src="' . $url . '">';
}
If you fetch the path from the DB when generating each page, you increase traffic between your DB and your application. It takes some time, and possibly even some bandwidth if the DB is on another server.
If you fetch it from the DB only once and store it in the session, this overhead does not exist. However, if the path changes (e.g. when the user changes his/her profile image), the value in session must be refreshed. Maintaining consistency between the session and the DB might need some effort – you’d need to update both the DB and the session variable when you change the path (or create a new image for a user who hasn’t had one). Note that you have to call session_start()
before updating or using session variables.
I would personally choose to fetch the value from the DB only once and cache it in the session. I would load the path from the DB immediately after session_start()
if it has not been loaded yet, so that I did not need to test for the session variable being set when generating the HTML.
<?php
…
session_start();
if (!isset($_SESSION['userimage'])) {
$_SESSION['userimage'] = loadUserImageFromDB();
}
…
?>
…
<img src="<?php echo $_SESSION['userimage'];?>"/>
…