Payne's SQL Note #2

Back to Payne's SQL Notebook


Create and Close a MySQL Connection, Create and Delete A Database

1. Create and Close a Connection to a Database

// Create a connection.
$connection = mysql_connect("serverName", "userName", "password");

// Close a connection.
mysql_close($connection);

2. Create A Database

SyntaxExample
// Create a database.
$query = "CREATE DATABASE database_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());
}

// Create a database
if (mysql_query("CREATE DATABASE ReferenceDB", $con))
{
    echo "Query processed.";
}
else
{
    echo "Error Message: " . mysql_error();
}

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

?>

3. Delete A Database

SyntaxExample
// Delete a database
$query = "DROP DATABASE database_name";

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

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

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

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

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

?>