sunshinekitty sunshinekitty - 7 days ago 8
MySQL Question

How can I Fetch data and retrieve only first column by this statement using PDO?

As the title states, I am only able to grab the id column, I am getting an Undefined index error for the others.

My code:

if(isset($_SESSION['id'])) {
$presh = $_SESSION['id'];
$stmt = $pdo->prepare("SELECT id FROM users WHERE id = :id");
$id = $presh;
$stmt->execute(array(':id'=>$id));
$accountinfo = $stmt->fetch(PDO::FETCH_ASSOC);
}


Later on in my code I reference it as such:

Karma <span id="kcurrent"><?php echo $accountinfo["karmacurrent"]; ?></span> | <span id="ktotal"><?php echo $accountinfo["karmatotal"]; ?></span>


The rows do exist and they are filled, what am I doing wrong?

Answer

You can only select the id column because that is all you have in the query.

Try something like this

if(isset($_SESSION['id'])) {
$presh = $_SESSION['id'];
    $stmt = $pdo->prepare("SELECT id, karmacurrent FROM users WHERE 
                                        id = :id
                                        ");
        $id = $presh;
        $stmt->execute(array(
                                        ':id'=>$id
                                        ));
    $accountinfo = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

Basically you were only retrieving the ID from the table instead of the other columns.