PHP SELECT IMAGE from MYSQL-ThrowExceptions

Exception or error:

My goal is to show the image from the MYSQL “images / upload / …
But my code said that i have a undefined error on:

        $user_id = $_SESSION['user']['id'];
    $caminhoImagem = $_SESSION['user']['imagem_perfil'];

    if(DBGetImagemDoUser($user_id) == True)

Someone can help me?

All Code:

$user_id = $_SESSION['user']['id'];
$caminhoImagem = $_SESSION['user']['imagem_perfil'];

if (DBGetImagemDoUser($user_id) == True) {
    echo "<p class='pull-right'><img src='" . $caminhoImagem . "'>  </p>";
}

function DBGetImagemDoUser($user_id)
{
    //SELECT imagem_perfil FROM users WHERE id={$id_do_user}

    global $host, $dbname, $username, $password, $options;
    $dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
    $procurarUser = $dbh->prepare("SELECT imagem_perfil FROM users WHERE id='user_id'");
    $procurarUser->execute();
    $checkUser = $procurarUser->fetchAll();
    //$caminhoImagem = DBGetImagemDoUser['imagem_perfil'];

    if (count($caminhoImagem) > 0) {
        $user_id = $caminhoImagem['imagem_perfil'];
    } else {
        return False;
    }
    return $user_id;
}
How to solve:

I am not sure if this is the solution to all your problems as I do not understand your question completely, but this line is wrong

 $procurarUser = $dbh->prepare("SELECT imagem_perfil FROM users WHERE id='user_id'");

It should probably be

$procurarUser = $dbh->prepare(“SELECT imagem_perfil FROM users WHERE id=’$user_id'”);

SECOND ANSWER:
Your issue is with variable scope.

The $caminhoImagem is not visible from inside the function.

And also you are not getting the value retrieved from the database and returning it in any way. This is not a very elegant solution but it fits with your original script with minimal changes.

$user_id = $_SESSION['user']['id'];
$caminhoImagem = '';

if (DBGetImagemDoUser($user_id) !== false) {
    echo "<p class='pull-right'><img src='" . $caminhoImagem . "'>  </p>";
}

function DBGetImagemDoUser($user_id)
{
    global $host, $dbname, $username, $password, $options, $caminhoImagem;

    $dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
    $procurarUser = $dbh->prepare("SELECT imagem_perfil FROM users WHERE id='$user_id'");
    $procurarUser->execute();
    $Users = $procurarUser->fetch();

    if ( $users === false ) {
        return false;
    } else {
        $caminhoImagem = $Users['imagem_perfil'];
    }
    return true;
}

Answer´╝Ü

Try with:

$procurarUser = $dbh->prepare("SELECT imagem_perfil FROM users WHERE id=?");

$procurarUser->bind_param('s', $user_id);

$procurarUser->execute();

bind_param() is used to bind values of its parameters to the ‘?’ Inserted in the query, following formats indicated in the string (here we use ‘s’ to indicate a string)

Leave a Reply

Your email address will not be published. Required fields are marked *