Search code examples
phpsqlpdocreate-table

PDO not creating CREATE TABLE


I'm pretty new to this and need some help.

I am trying to input an array into a PDO database; the database is created using this code:

$createdb = $db->exec("CREATE DATABASE $validdbname;
CREATE USER '$user'@'localhost' IDENTIFIED BY '$password';
GRANT ALL ON `$validdbname` .* TO '$user'@'localhost';
FLUSH PRIVILEGES;")
or die(print_r($db->errorInfo(), true));
// Check for success
if ($createdb) 
{
    echo 'Database Created!<br /><br />';
}
else echo "Database not successfully created! <br /><br />";

This works successfully, however when I attempt to create a table within the created database with very similar code, this does not work:

$createtable = $db->exec("CREATE TABLE IF NOT EXISTS webdata (
id INTEGER NOT NULL AUTO_INCREMENT,
data VARCHAR(200) NOT NULL,
PRIMARY KEY (id))")

or die(print_r($db->errorInfo(), true));

I have checked on PHPMyAdmin to see if a table has been created, which while databases have been created the tables aren't. This is the error that shows:

Array ( [0] => 00000 [1] => [2] => )

I would be happy to give more code or information if necessary. I just cannot work out why this is happening and would greatly appreciate any input, thanks.


Solution

  • You need to

    $db->exec('USE ' . $validdbname);
    

    between the two queries, or use a fully qualified name in the CREATE TABLE:

    CREATE TABLE IF NOT EXISTS $validdbname.webdata ( ...