php - PDO creating database and tables -
i'm struggling assignment. create php script create database , tables database. have been able cobble script create database reading here , w3schools, stumped how have same script create tables on new database. here's have create new database:
<?php $servername = "localhost"; $username = "root"; $password = "mysql"; try { $conn = new pdo("mysql:host=$servername", $username, $password); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql = "create database if not exists musicdb"; $conn->exec($sql); echo "db created successfully"; } catch(pdoexception $e) { echo $sql . "<br>" . $e->getmessage(); } $conn = null; ?>
i tried follow on create tables this:
<?php $servername = "localhost"; $username = "root"; $password = "mysql"; try { $conn = new pdo("mysql:host=$servername", $username, $password); $conn->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->exec($sql); echo "db created successfully"; } catch(pdoexception $e) { echo $sql . "<br>" . $e->getmessage(); } $conn = null; ?>
however not working , 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
basically, how tell script use newly created table , create tables it? , know username , password showing running on laptop , never anywhere i'm not worried.
you're executing last statement. keep assigning $sql
, not executing statements.
try { $conn = new pdo("mysql:host=$servername", $username, $password); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql = "create database if not exists musicdb"; $conn->exec($sql); $sql = "use musicdb"; $conn->exec($sql); $sql = "create table if not exists artists ( id int(11) auto_increment primary key, artistname varchar(30) not null)"; $conn->exec($sql); echo "db created successfully"; } catch(pdoexception $e) { echo $sql . "<br>" . $e->getmessage(); }
Comments
Post a Comment