Errors with $fetch variable

Hello guys. I know this might sound like a really stupid question but Im really a beginner. Im learning PHP, HTML and others due to school. I wanted to create a simple registration and login page with profiles using databases. But… its quite hard and I dont really know what I am doing haha… And I got a few errors after “copying” some youtube tutorials.

ERRORS:
Warning : Undefined array key “image” in C:\Users\windows\PhpstormProjects\skolakrizik_volby\php\profile.php on line 75
Profilový obrázek

Warning: Undefined array key “username” in C:\Users\windows\PhpstormProjects\skolakrizik_volby\php\profile.php on line 82

I am using localhost database via Xampp.

If anyone could advise me how to fix the errors I would be very grateful. PS: the code will probably be one big mess, sorry :smiley:

LINK (google drive)

What does adding var_dump($fetch); show?

I found out it only happens after refreshing the page.
normal:

after refreshing (or clicking the profil again)
(next post)


the var_dump before refresh:

array(5) { [“id”]=> string(2) “30” [“name”]=> string(0) “” [“username”]=> string(4) “pepa” [“password”]=> string(60) “$2y$10$xaj4zleb0IT9FFIFprzqNeuP2sktxLRPOa0ZpN7WqLPrj3nrlrDDy” [“image”]=> string(0) “” }

and var_dump after refresh:
array(0) { }

Your code is clearing the session variable if fetch[‘image’] is an empty string. Why is it doing that?

Welp, I wish I knew but I don’t :smiley:

The profile page ‘requires’ a logged in user in order to display that user’s data. If there is a logged in user, you would query to get that user’s data. If the query doesn’t match a row of data, which would be due to either a programming mistake or the row of data has been deleted (which would almost never occur in a real application), you would typically just display a message that “no user data was found”, and skip over attempting to display the user data.

In the current code, the profile image is optional, because it is outputting a default image is there isn’t an actual profile image. The current logic for - Pokud uživatel neexistuje, odstraňte uživatelské ID z relace shouldn’t even be testing if the image element is an empty string.

To test if a row of data was or was not found, you would test if the $fetch variable is either directly a true or false boolean value. e.g. if($fetch) … or if(!$fetch), or if it is not empty() or is empty() to decide what to do on the page.

Here’s a list of points about the profile code -

  1. use ‘require’ for things your code must have
  2. the isset( session variable ) … logic can be replaced with - $user_id = $_SESSION['user_id']??'';
  3. the only piece of user data that you should put into a session variable to identify who the logged in user is, is the user id (which is what this code is using.) you should query on each page request to get any other user data, such as the username, permissions, … some of the code is using a session variable for the username and the logout code is clearing the username session variable, which will allow the profile code to still work, since it is using the user_id session variable.
  4. you should build sql query statements in a php variable. this makes debugging easier.
  5. you should list out the columns you are SELECTing in a query and only select the columns you need for the current task
  6. you should use a prepared query instead of putting dynamic values directly into the sql query statement. if it seems like using the mysqli extension is overly complicated when dealing with prepared queries, it is. this would be a good time to switch to the much simpler and better designed PDO extension.
  7. don’t use or die(...) for error handling. modern php (php8+) uses exceptions for errors by default.
  8. don’t use _num_rows to test if a query matched or didn’t match any data. just fetch the data and test of there was or was not fetched data.

Here’s what the profile code would look like using these suggestions -

<?php
session_start();

require 'db.php';

// Získání ID uživatele z relace
$user_id = $_SESSION['user_id']??'';

// Inicializace proměnné
$fetch = [];

// Pokud je uživatelské ID k dispozici, proveďte dotaz na databázi
if($user_id)
{
	$sql = "SELECT username, image FROM users WHERE id=?";
	$stmt = $pdo->prepare($sql);
	$stmt->execute([ $user_id ]);
	$fetch = $stmt->fetch(); // this will either be the fetched row of data or a boolean false
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/html/profile.css">
    <title>VOLBY FOTEK - ŠKOLA KŘIŽÍK</title>
    <link rel="icon" type="image/x-icon" href="/icon.png">
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Fetch login status from the server
            fetch('/skolakrizik_volby/php/check_login.php')
                .then(response => response.json())
                .then(data => {
                    const navMenu = document.getElementById('nav-menu');
                    if (data.logged_in) {
                        // User is logged in
                        navMenu.innerHTML += `
                            <li><a href="/skolakrizik_volby/php/profile.php">Profil</a></li>
                        `;
                    } else {
                        // User is not logged in
                        navMenu.innerHTML += `<li><a href="/skolakrizik_volby/html/login.html">Login</a></li>`;
                    }
                })
                .catch(error => console.error('Error fetching login status:', error));
        });
    </script>
</head>
<body>
<div class="menu">
    <div class="header">
        <h1>VOLBY FOTEK - ŠKOLA KŘIŽÍK</h1>
        <nav>
            <ul id="nav-menu">
                <li><a href="/skolakrizik_volby/html/index.html">Domů</a></li>
                <li><a href="/skolakrizik_volby/html/galerie.html">Galerie</a></li>
                <li><a href="/skolakrizik_volby/html/home.html">Hlasování</a></li>
                <li><a href="/skolakrizik_volby/html/upload.html">Upload</a></li>
            </ul>
        </nav>
    </div>
    <div class="container">
        <div class="profile">
			<?php
			if(!$fetch)
			{?>
				<p>no user data was found</p>
			<?php
			}
			else
			{
				if($fetch['image'] == '') {
					echo '<img src="/skolakrizik_volby/uploaded_img/default.jpg" alt="Profilový obrázek">';
				} else {
					echo '<img src="/skolakrizik_volby/uploaded_img/'.$fetch['image'].'" alt="Profilový obrázek">';
				}
			?>
            <h3><?=$fetch['username']?></h3>
            <a href="/skolakrizik_volby/php/logout.php">Odhlásit</a>
            <a href="/skolakrizik_volby/php/update_profile.php">Upravit</a>
			<?php
			}
			?>
        </div>
    </div>
</div>
</body>
</html>

It seems like its working! Thank you!

Sponsor our Newsletter | Privacy Policy | Terms of Service