Payne's SQL Note #3

Back to Payne's SQL Notebook


Create and Delete A Table

1. Create A Table

SyntaxExample
// Select a database.
mysql_select_db("databaseName", $connection);

// Query: create a table.
$query = "CREATE TABLE table_name(
    column_name_1 data_type,
    column_name_2 data_type,
    column_name_3 data_type,
    ...)";

// Send the query.
$returnValue = mysql_query($query, $connection);
<?php

// Create a connection to a MySQL RDBMS.
$con = mysql_connect("localhost", "username", "password");

// If the connection fails, display error message.
if (!$con)
{
    die('Error connecting to MySQL: ' . mysql_error());
}

// Select a database
mysql_select_db("ReferenceDB", $con);

// Query: Create a table
$sql = "CREATE TABLE ReferenceTB(
    ArticleID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    PMID int,
    Author TEXT,
    Title varchar(250),
    Journal varchar(50),
    Year int)";

// Send the query.
if (mysql_query($sql, $con))
{
    echo "Query processed.";
}
else
{
    echo "Error Message: " . mysql_error();
}

// Close the connection.
mysql_close($con);

?>

2. Delete A Table

SyntaxExample
// Query: Delete a table.
$query = "DROP TABLE table_name";

// Send the query.
$returnValue = mysql_query($query, $connection);
<?php

// Create a connection to a MySQL RDBMS.
$con = mysql_connect("localhost", "username", "password");

// If the connection fails, display error message.
if (!$con)
{
    die('Error connecting to MySQL: ' . mysql_error());
}

// Select a database.
mysql_select_db("ReferenceDB", $con);

// Delete a table.
if (mysql_query("DROP TABLE ReferenceTB", $con))
{
    echo "Query processed.";
}
else
{
    echo "Error Message: " . mysql_error();
}

// Close the connection.
mysql_close($con);

?>