blackbox64
blackbox64

Reputation: 1

values are not being returning from the database PHP

new here and I am at my wits end with this problem. The pretence is simple; I am trying to select a user id from the database BASED on a value from a session cookie. I have confirmed that the SQL works as I have run it through sql itself, and the only thing I can think of is that it's not executing or my fetch or bind is wrong.

<?php
session_start();
$cart = $_SESSION["cart"];

try{
require "connect.php";
$id = "SELECT id_no FROM eCustomer WHERE surname = :uid";
echo $id . '<br />';

$idfetch=$dbh->prepare($id);
$idfetch->bindValue(":uid", $_SESSION["uid"]);
$idfetch->execute();

$customer_id = $idfetch["id_no"];

echo $customer_id;

$dbh=null;

} catch (PDOExeption $e){
   echo $e;
}
?>

This should echo to my browser

SELECT id_no FROM eCustomer WHERE surname = :uid
1

But it's only outputting

SELECT id_no FROM eCustomer WHERE surname = :uid

I have also tried putting the session variable directly into the sql statement without the bindValue

$id = "SELECT id_no FROM eCustomer WHERE surname = '" . $_SESSION["uid"] . "'";

Which outputs to my browser

SELECT id_no FROM eCustomer WHERE surname = 'Mclellan'

(Mclellan being in my session cookie)

Any help would be greatly appreciated.

Upvotes: 0

Views: 47

Answers (2)

Gluzzer
Gluzzer

Reputation: 120

It looks like you are missing the actual fetching of the results

you would need a line like below following your $idfetch->execute();

$customerid = $idfetch->fetch(PDO::FETCH_ASSOC);

after that your echo $customerid["id_no"]; should work.

The reason being is that all you have had php do is execute the query without telling it to fetch the results from the query.

Also, the above is for using PDO as that is what it looks like you are using. If you are using mysqli then this probably wont help.

Upvotes: 2

Kevin
Kevin

Reputation: 41885

You have actually executed the statement, but you haven't actually ->fetch()ed it yet. You missed that part:

$results = $idfetch->fetchAll(PDO::FETCH_ASSOC);
// print_r($results);
foreach($results as $row) {
    echo $row['id_no'];
}

Sidenote:

If you only require one row, then a single ->fetch() invocation should suffice:

$row = $idfetch->fetch(PDO::FETCH_ASSOC);
echo $row['id_no'];

Upvotes: 3

Related Questions