Jump to content

pass PDO object as a variable in html


osherdo
Go to solution Solved by mac_gyver,

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
Share on other sites

  • Solution

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.