-2

Here is our db.php

$host = 'localhost';
$username = 'root';
$password = '';
try
{
    $conn = new PDO("mysql:host=".$host.", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "CREATE DATABASE IF NOT EXISTS teacher";
    $conn->exec($sql);
    $sql = "use teacher";
    $conn->exec($sql);
}
catch(PDOException $e)
{
    echo "Error".$e->getMessage();
}

..

There was an error!

Parse error: syntax error, unexpected 'CREATE' (T_STRING) in

How to solve this.

sharinell
  • 11
  • 3

1 Answers1

2
$conn = new PDO("mysql:host=".$host.", $username, $password);
                ^           ^       ^
                1           2       3

Double-quote 1 starts a string.

Double-quote 2 ends a string.

Double-quote 3 starts a string.

That string is not closed until here:

$sql = "CREATE ...
       ^
       4

Double-quote 4 ends the string.

Which means CREATE is being interpreted as a PHP keyword, not as part of a string.

TIP: You can put variables inside a double-quoted string. This makes it much easier to avoid this type of imbalanced-quote mistake.

$conn = new PDO("mysql:host=$host", $username, $password);
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • That sounds a little scary. Thanks for the info. – sharinell Aug 20 '18 at 16:05
  • If that mistake wasn't obvious, make sure you're using a syntax highlighting code editor. These usually point out small but important mistakes as you're working, saving you a lot of time tracking them down and fixing them later. – tadman Aug 20 '18 at 16:26
  • Even the basic syntax highlighting StackOverflow does shows this error. – Mike Aug 21 '18 at 02:00
  • Yes, but it's pretty subtle. You really have to know what you're looking for. – Bill Karwin Aug 21 '18 at 02:08