-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];
}
?>
3
  • 2
    You're adding paramters to your prepared statement; but there are no placeholders to bind them to. try SELECT * FROM users WHERE name=? AND id=? Commented May 7, 2013 at 12:35
  • I'd say they rather want to bind them as a result Commented May 7, 2013 at 12:36
  • 1
    FYI the database isn't phpmyadmin, it is a mysql database, phpmyadmin is just a tool to see the data in the mysql database. Commented May 7, 2013 at 12:38

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

wow thx, that was a really stupid fault. My bad :/
Its cool it happens to the best of us. Happy Coding!!
To make such things impossible to happen, one have to have error reporting on
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'];
}

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.