title: PDO creating database and tables
body: <p>I'm currently struggling with an assignment. I am to create a PHP script that will create a database and all the tables for that database. I have been able to cobble together the script to create the database itself from reading here and W3Schools, however I am stumped as to how to have the same script create tables on that new database. Here's what I have to create a new database:</p>
  
  <pre><code>&lt;?php
  $servername = "localhost";
  $username = "root";
  $password = "mysql";
  
  try {
  $conn = new PDO("mysql:host=$servername", $username, $password);
  $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "CREATE DATABASE IF NOT EXISTS musicDB";
  $conn-&gt;exec($sql);
  echo "DB created successfully";
  }
  catch(PDOException $e)
  {
  echo $sql . "&lt;br&gt;" . $e-&gt;getMessage();
  }
  
  $conn = null;
  ?&gt;
  </code></pre>
  
  <p>I tried to follow on that to then create tables with this:</p>
  
  <pre><code>&lt;?php
  $servername = "localhost";
  $username = "root";
  $password = "mysql";
  
  try {
  $conn = new PDO("mysql:host=$servername", $username, $password);
  $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = "CREATE DATABASE IF NOT EXISTS musicDB";
  $sql = "use musicDB";
  $sql = "CREATE TABLE IF NOT EXISTS ARTISTS (
  ID int(11) AUTO_INCREMENT PRIMARY KEY,
  artistname varchar(30) NOT NULL)";
  $conn-&gt;exec($sql);
  echo "DB created successfully";
  }
  catch(PDOException $e)
  {
  echo $sql . "&lt;br&gt;" . $e-&gt;getMessage();
  }
  
  $conn = null;
  ?&gt;
  </code></pre>
  
  <p>However that is not working and I get the following error: CREATE TABLE IF NOT EXISTS ARTISTS ( ID int(11) AUTO_INCREMENT PRIMARY KEY, artistname varchar(30) NOT NULL)
  SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected</p>
  
  <p>Basically, how do I tell the script to use the newly created table and then create tables for it? And I know the username and password are showing but this is running on my laptop and will never be anywhere so I'm not worried.</p>