Question

I don´t know why PHP returns always false, when I try to to execute a SELECT query with fetching a single row.

My tables are:

create table profile
(
    id int not null auto_increment,
    email char(50) not null,
    password char(100) not null,
    name char(100) not null,
    surname char(50) not null,
    street char(50) not null,
    homeno char(5) not null,
    postalcode char(5),
    homearea char(100) not null,
    group_id int not null,
    primary key(id)
);
create table usergroups
(
    id int auto_increment not null,
    name char(30) not null,
    primary key(id)
);

I got some datasets in it and then I try to read them with (for fetching one user profile; simplified example):

$sSQL = <<<SQL
SELECT `profile`.`id` AS `profile.id`, `profile`.`email` AS `profile.email`, `profile`.`password` AS `profile.password`, `profile`.`name` AS `profile.name`, `profile`.`surname` AS `profile.surname`, `profile`.`street` AS `profile.street`, `profile`.`homeno` AS `profile.homeno`, `profile`.`postalcode` AS `profile.postalcode`
FROM `profile`
inner join `usergroups` on `profile`.`group_id` = `usergroups`.`id`
WHERE `profile`.`email` = ?
SQL;
$pdo = new PDO($sDsn, $sUser, $sPass);
$stmt = $pdo->prepare($sSQL);
$sEmail = 'some@example.com';
$stmt->bindValue(1, $sEmail, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch();
var_dump($result);

My database is a MariaDB.

The same query has worked before without a question mark in it, so there was nothing to bind before. I guess there is an mistake with database and/or PHP.

Was it helpful?

Solution

Programming is not something like fiction literature. Every premise have to be verified.

$pdo = new PDO($sDsn, $sUser, $sPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sSQL = SELECT p.* FROM profile inner join usergroups u on group_id = u.id 
        WHERE email = 'some@example.com';
$user = $pdo->query($sSQL)->fetch();
var_dump($user);

$sSQL = SELECT p.* FROM profile inner join usergroups u on group_id = u.id 
        WHERE email = ?;
$stmt = $pdo->prepare($sSQL);
$stmt->execute(['some@example.com']);
$user = $stmt->fetch();
var_dump($user);

run this code and paste result here. Or just consider it yourself

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top