简体   繁体   中英

Trying to Create a Profile Image system

I'm trying to create a profile image upload system on my page, but I'm having a challenge, the pictures echo four times, the default picture displays four times on the page and when I upload a picture it does the same. I need help on how to resolve this, I need only one image displaying on the page.

<?php
require("./includes/databaseHandler.php");
$id = $usersData['id'];

$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);

if(mysqli_num_rows($result) > 0 ){
    while(mysqli_fetch_assoc($result)){
        $sqlImg = "SELECT * FROM profileimg WHERE userid = '$id'";
        $resultImg = mysqli_query($con, $sqlImg);
        while($rowImg = mysqli_fetch_assoc($resultImg)){
            echo "<div class='user-container'>";
                if($rowImg['status'] == 0){
                    echo "<img src = 'uploads/profile".$id.".jpg' >";
                }else{
                    echo "<img src = 'uploads/profiledefault.jpg'>";
                }
            echo "</div>";
        }
    }
}

?>

You are not fetching the result of the first query into a usable variable, so you dont have the $id set for each user returned by the first query

NOTE: Your script is open to SQL Injection Attack . Even if you are escaping inputs, its not safe! You should consider using prepared parameterized statements in either the MYSQLI_ or PDO API's instead of concatenated values

So I have also made use of prepared parameterised statements in my answer.

<?php
require("./includes/databaseHandler.php");

// I assume this was a fudge to get it working
//$id = $usersData['id'];

$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);

if(mysqli_num_rows($result) > 0 ){

    // prepare query here ONCE and use it may times with amended parameters    
    $sqlImg = "SELECT * FROM profileimg WHERE userid = ?";
    $stmt = $con->prepare($sqlImg);

    while($user = $result->fetch_assoc()){
    //    ^^^^^
        $stmt->bind_param('i', $user['id']);
        $stmt->execute();
        $result = $stmt->get_result();

        while($rowImg = $result->fetch_assoc()){
            echo "<div class='user-container'>";
                if($rowImg['status'] == 0){
                    echo "<img src = 'uploads/profile" .$user['id']. ".jpg' >";
                }else{
                    echo "<img src = 'uploads/profiledefault.jpg'>";
                }
            echo "</div>";
        }
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM