0

I'm 'Connected to database'. There is no data in the table, and $result doesn't echo anything. Even though I'm 'Connected to database', the error is as follows:

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

I've read the relevant postings, with no luck.

<?php
include("/directory outside of html/db.php");

try {
    $dbh = new PDO("mysql:host=$host;database=$database", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//try to insert data
$fname = 'BOB';
$lname = 'JONES';
$email = '[email protected]';
$phone = '410-310-3456';
$resident = TRUE;
$age = '25=30';
$zip = '23456';
$result = FALSE;

  $stmt = $dbh->prepare('INSERT INTO volunteers
  (
   lname,
   fname,
   email,
  )

VALUES
  (
    :lname,
    :fname,
    :email,
  )');

 $result = $stmt->execute(array(
    ':lname' => $lname,
    ':fname' => $fname,
    ':email' => $email,
  ));

echo $result;   

//catch any errors from try()
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>
1
  • Echo "mysql:host=$host;database=$database" before you call new PDO Commented Nov 24, 2012 at 18:31

1 Answer 1

3

Use dbname= instead of database= , like this:

$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);

Alternatively, you can select later a different database with USE, like this:

$dbh->query("use newdatabase");
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent - did the trick. I also had to remove the commas after email. Thanks!
By the way, as you seem new to StackOverflow, remember to accept the answer (check mark below the score number) so both of us get rewarded points ;-) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.