Since no rows affect the creation of the table $ createTable returns 0, see the manual
PDO :: exec () returns the number of rows that have been modified or deleted by the SQL statement. If no lines were affected, PDO :: exec () returns 0.
Since you are creating a table, you will be free from SQL injection if the column names are hard-coded (as in the code below). I left $table = "tcompany"; , since you want to print the created table (I would leave it myself)
I added error handling , which will display errors in the try block.
$table = "tcompany"; try { $db = new PDO("mysql:dbname=mydb;host=localhost", "root", "" ); $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );//Error Handling $sql ="CREATE table $table( ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY, Prename VARCHAR( 50 ) NOT NULL, Name VARCHAR( 250 ) NOT NULL, StreetA VARCHAR( 150 ) NOT NULL, StreetB VARCHAR( 150 ) NOT NULL, StreetC VARCHAR( 150 ) NOT NULL, County VARCHAR( 100 ) NOT NULL, Postcode VARCHAR( 50 ) NOT NULL, Country VARCHAR( 50 ) NOT NULL);" ; $db->exec($sql); print("Created $table Table.\n"); } catch(PDOException $e) { echo $e->getMessage();//Remove or change message in production code }
NOTE in response to using a comment
CREATE TABLE IF NOT EXISTS
david strachan
source share