deepak yadav
deepak yadav

Reputation: 19

PHP PDO database connection

Hey fellas No idea what i'm doing wrong already tried all suggested idea on stackoverflow still not resolving error no database selected.

code:

<?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 code:

<?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.";    
?>

you can see error in image. please help me resolve this. enter image description here

Upvotes: 1

Views: 989

Answers (1)

abetwothree
abetwothree

Reputation: 585

It looks like your connection to your database is wrong, since the error message of no database selected where to create your table to. Here is how to connect with 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.";

?>

Try that and see if it works for you.

Upvotes: 1

Related Questions