-3

I want to retrieve data from my database 'phpopdracht5' with table 'users' and attributes 'name' (VARCHAR(20)) and 'id' (INTEGER), but it's just not working. There must be something wrong with my code

<?php
define("DB_HOST", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "phpopdracht5");

try
{
    $db_conn = new  PDO('mysql:host='.DB_HOST.';dbname'.DB_NAME,DB_USERNAME,DB_PASSWORD);
}
catch(PDOException $e)
{
print "Error!:".$e->getMessage()."\n";
die();
}

$sth = $db_conn->prepare('SELECT * FROM users'); 
$sth->bindParam(':name', $name, PDO::PARAM_STR, 20);
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->execute();

while ($row = $sth->fetch(PDO::FETCH_BOTH)) {
echo $row[0];
}
?>
breght
  • 57
  • 10

3 Answers3

1

You bind params which didn't exist on your query. Your query must be:

SELECT * FROM users WHERE name = :name AND id = :id

Otherwise if you want all your users:

$sth = $db_conn->prepare('SELECT id, name FROM users'); 
$sth->execute();

while ($row = $sth->fetch(PDO::FETCH_BOTH)) {
echo $row['id'] . ':' . $row['name'];
}
antoox
  • 1,309
  • 11
  • 9
1

you don't need to bind parameters to get them. just

$sth = $db_conn->prepare('SELECT * FROM users'); 
$sth->execute();

Also, you have to set up PHP and PDO error reporting as explained here: PDO query fails but I can't see any errors. How to get an error message from PDO?

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

It looks like you are missing an equals sign or two:

This is your pdo command: $db_conn = new PDO('mysql:host='.DB_HOST.';dbname'.DB_NAME,DB_USERNAME,DB_PASSWORD);

this is a different user's one: $db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass'); Link: DEBUG PDO Connection & PHP Output

So it looks like "dbname=" is missing

Community
  • 1
  • 1
greendave11
  • 168
  • 1
  • 13