0

我'连接到数据库'。表中没有数据,并且 $result 没有回显任何内容。即使我'连接到数据库',错误如下:

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

我已经阅读了相关的帖子,没有运气。

<?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 = 'me@mymail.com';
$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();
    }
?>
4

1 回答 1

3

使用dbname=代替database=,像这样:

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

或者,您可以稍后使用 选择不同的数据库USE,如下所示:

$dbh->query("use newdatabase");
于 2012-11-24T18:32:27.530 回答