0

I have this code for fetching data in pdo from my database:

<?php 
$stmt = $pdo->query('SELECT `email` FROM hptenant WHERE user_id=:user_id');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo $row['email'] . "\n";
} ?>

But anytime I use it, it will blank my page, that is nothing after this code will show (HTML). However if I use this one,

<?php $stmt = $pdo->query('SELECT `email` FROM hptenant');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo $row['email'] . "\n";
} ?> 

It will show me the emails in my database. Can somebody help me please?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Zikskonect
  • 17
  • 3
  • I don't see where you are passing `:user_id`. If you pass nothing to a query that is set to pull a row of data based on a variable, what do you expect to happen? – GrumpyCrouton Apr 29 '19 at 15:51
  • 3
    You need to prepare, then either execute or bind/execute. You can't use bound parameters with `query` – aynber Apr 29 '19 at 15:52
  • It may be worth enabling some form of error reporting (if you haven't already) - https://stackoverflow.com/questions/8776344/how-to-view-query-error-in-pdo-php gives one solution. – Nigel Ren Apr 29 '19 at 16:00

1 Answers1

2

Looks like you aren't binding anything to :user_id

$stmt = $pdo->prepare('SELECT `email` FROM hptenant WHERE user_id=:user_id');
$stmt->bindParam(':user_id', $USER_ID_HERE);
$stmt->execute();
// while loop was unnecessary here (assuming user_id is unique)
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['email'] . "\n";
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
John
  • 577
  • 4
  • 20
  • 3
    The `WHILE` loop is not necessary here, assuming no 2 users will have the same `user_id` (which they shouldn't). – GrumpyCrouton Apr 29 '19 at 15:53
  • @GrumpyCrouton I'm sure but I didn't want to stray from the original code. – John Apr 29 '19 at 15:54
  • 2
    I don't think fixing an oversight would be straying from the original code, and it's probably better to show op the _correct_ way to do it. This loop adds unneeded overhead that the OP may not realize. – GrumpyCrouton Apr 29 '19 at 15:55
  • 1
    @GrumpyCrouton you're right, I've removed the unneeded loop – John Apr 29 '19 at 16:00
  • @John, Please let me ask this sort of 'silly' question, what is the difference between the user_I'd that I used and the suggested $USER_ID_HERE. Is it something I need to declare? I am new to PHP especially PDO so bear with my question. – Zikskonect Apr 29 '19 at 16:03
  • You need to pass the desired user_id to bindParam so you can get the correct user from the database. – John Apr 29 '19 at 16:06