|
<?php /* This script will create a database, if not present by setting $dbCreateIfNotPresent to 1 (may need additional permissions for this action). This script will also create a new table and get data out of that new table. */ $dbCreateIfNotPresent = 0; /* If my database does not exist but I want it created, set this to 1. Otherwise, set this to 0. */ $mySQLDatabaseName = "may be user name, account name, etc"; /* The name of my database where all my tables are at */ $mySQLConnection = mysql_connect("localhost", "user", "password"); /* The connection string to my database */ /* Let's do something */ if (!$mySQLConnection) { /* Could not connect due to an error */ die('Error connecting to mySQL: ' . mysql_error()); } else { /* Point to my database */ if (mysql_select_db($mySQLDatabaseName, $mySQLConnection)) { /* Let's design a new table. uniqueID serves as the auto-incrementing primary key */ $mySQLParameters = "CREATE TABLE myTable (uniqueID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(uniqueID), FirstName varchar(15), LastName varchar(15), Age int)"; /* Let's create the new table */ if (mysql_query($mySQLParameters, $mySQLConnection)) { echo "The new table was created. "; /* Let's insert a row of data into the new table we just created */ $insertMySQLData ="INSERT INTO myTable (FirstName, LastName, Age) VALUES ('fname', 'lname', 99)"; if (mysql_query($insertMySQLData, $mySQLConnection)) { echo "The new row of data was inserted into the new table we just created. "; /* Let's select the new row of data we just inserted into the table */ $rowsOfDataFromTable = mysql_query("SELECT * FROM myTable"); while($singleRowOfData = mysql_fetch_array($rowsOfDataFromTable)) { echo "PK = " . $singleRowOfData['uniqueID'] . ", FirstName = " . $singleRowOfData['FirstName'] . ", LastName = " . $singleRowOfData['LastName'] . ", Age = " . $singleRowOfData['Age'] . "<br />"; } } else { /* Could not insert new row of data into the table. Let's see why. */ echo "Error inserting row of data into table: " . mysql_error(); } } else { /* Could not create the new table. Let's see why. */ echo "Error creating the new table: " . mysql_error(); } } else { if ($dbCreateIfNotPresent == 1) { if (mysql_query("CREATE DATABASE " . $mySQLDatabaseName, $mySQLConnection)) { echo "Database \"" . $mySQLDatabaseName . "\" created. The new table, if you defined one in this script, was not created. You will need to run this script again in order to create the new table in the database that was just created."; } else { echo "Error creating new database \"" . $mySQLDatabaseName . "\": " . mysql_error(); } } else { /* Could not connect to my database. Let's see why. */ echo "Error connecting to database \"" . $mySQLDatabaseName . "\": " . mysql_error(); } } /* Let's close the database connection now that we are done */ mysql_close($mySQLConnection); } ?> |