Jump to content

pass PDO object as a variable in html


osherdo

Recommended Posts

So I have this code:

<?php
$user = "clicrckc_osherdo";
$pass = "3563077";
$CurrentUser=  $_SESSION['user_id'];


try {
    $dbh = new PDO('mysql:host=localhost;dbname=clicrckc_andfit', $user, $pass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "connected successfully";
    print_r($_SESSION);
    $UserName = $dbh->prepare("SELECT first_name,last_name FROM users WHERE user_id = ?"); 
    $UserName->bindParam(1, $CurrentUser);
    $UserName->execute();
    $UserName->fetch(PDO::FETCH_ASSOC);
    $dbh = null;
    
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

?>

<div id="PersonalDetails">Hello dear <?= $UserName ?>!</div>

I am trying to insert the current username in the session to the html code where $Username is. I cannot find out why it wont work. I am getting the following message, instead of the current username in the session:

 

Catchable fatal error: Object of class PDOStatement could not be converted to string in/home/clicrckc/public_html/dashboard.phpon line136

 

I have tried to google the issue but I could not address the issue. 

 

please- help anyone?

 

Thank you.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/295186-pass-pdo-object-as-a-variable-in-html/
Share on other sites

the $UserName variable holds a PDOStatement object. your fetch statement (line 15 in the posted code) should assign the row that was fetched to a php variable. you can then access any of the elements of that array, such as the first_name. 

$row = $UserName->fetch(PDO::FETCH_ASSOC); // fetch the row

echo $row['first_name']; // display the first name

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.