PHP PDO数据库连接

时间:2016-02-09 18:42:46

标签: php database pdo

嘿fellas不知道我做错了什么已经尝试了stackoverflow上的所有建议的想法仍然没有解决错误没有选择数据库。

代码:

<?php    
  include 'db_connect.php';    
  // create client table

    try {    
          $sql = 'CREATE TABLE client (
                  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  name VARCHAR(40) NOT NULL,
                  phone INT NOT NULL,
                  email VARCHAR(60) NOT NULL,
                  address TEXT
          ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB';

          $pdo->exec($sql);

  }
  catch(PDOException $e) {    
          $error = 'Error creating customer table: '.$e->getMessage();    
          include 'error.html.php';    
          exit();    
  }

  $output = "Customer table created succesfuly";    
  include 'output.php';   
?>

db_connect.php代码:

<?php   
  $host = "localhost";
  $db = "hotelDB";
  $dbuser = "hotelAuth";
  $password = "+_90-w4903nsdkfn";    

  // connecting to DB using PDO

  try {    
      $pdo = new PDO("mysql:host = {$host}; dbname = {$db}", "{$dbuser}", "{$password}");    
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
      $pdo->exec('SET NAMES "utf8"');    
  }
  catch(PDOException $e) {    
      $error = "Error Occured While Connecting TO Database: ".$e->getMessage();    
      include 'error.html.php';    
      exit();    
  }    

  // On successful connection include booking form.    
    $ack = "Secure Connection established.";    
?>

你可以在图像中看到错误。请帮我解决这个问题。 enter image description here

1 个答案:

答案 0 :(得分:0)

看起来您与数据库的连接错误,因为没有数据库的错误消息选择了创建表的位置。以下是如何连接PDO:

<?php

    $dbuser = "hotelAuth";
    $password = "+_90-w4903nsdkfn";

    // connecting to DB using PDO
    try{

            $dbPDO = new PDO('mysql:host=localhost;dbname=hotelDB', $dbuser, $password);
            $dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec('SET NAMES "utf8"');
            echo "Connection was successful";

    } catch(PDOException $e){

            print "Error!: " . $e->getMessage() . "<br />";
            die();

    }

    // On successful connection include booking form.   
    $ack = "Secure Connection established.";

?>

试一试,看看它是否适合你。