-1

I am new to PDP PDO, this is my code to create a database named "title"

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "CREATE DATABASE title";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Database created successfully<br>";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage(); // THIS IS LINE NUMBER 17
    }

$conn = null;
?>

But this is the error, which i get, while i try to run the script

Notice: Undefined variable: sql in C:\xampp\htdocs\website\database\createdb.php on line 17

SQLSTATE[HY000] [1049] Unknown database 'myDB'

What is wrong?

Rahul Sharma
  • 15
  • 1
  • 6

2 Answers2

0

You connect to a db that is not existend here:

$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);

remove the dbname:

$conn = new PDO("mysql:host=$servername", $username, $password);
Jens
  • 67,715
  • 15
  • 98
  • 113
0

You are getting the SQL error on line #7 because you are trying to access myDB which doesn't exist yet and is throwing an exception.

You are getting the undefined variable error because the code in the try statement is failing before $sql is assigned to anything.

Jim Wright
  • 5,905
  • 1
  • 15
  • 34