Normally, when you are developing a PHP and MySQL web application, and you need to create a new database and one or more tables in that database, you would use an SQL script to do this. From time-to-time though, it's useful to be able to run a PHP script to create the database and tables. Here are a couple of PHP scripts that show how to do this.
Script 1 - Create the MySQL Database
<html><head><title>Create MySQL Database</title></head>
<body>
<?php
// This script creates a database on the MySQL server.
// The name of the database is db1.
//Connect to MySQL server
$link = mysql_connect("localhost");
// If you need to supply a username and password,
// then use the following line of code instead
// of the one above, substituting the correct
// username and password.
//$link = mysql_connect("localhost", "username", "password");
//If the connection cannot be made, display an error message
if (! $link)
die("Cannot connect to MySQL");
//Create a database called db1
mysql_create_db("db1")or die("Error: ".mysql_error());
//Close the connection to the MySQL server
mysql_close($link);
?>
</body>
</html>
Script 2 - Create a Table called 'user' in the Database
<html><head><title>Create Table in Database</title></head>
<body>
<?php
$db="db1";
$link = mysql_connect("localhost", "username", "password");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Select DB Error: ".mysql_error());
mysql_query("CREATE TABLE user( userID INT AUTO_INCREMENT, name VARCHAR(30), email VARCHAR(40), telephone VARCHAR(15), password VARCHAR(34), PRIMARY KEY(userID))");
mysql_close($link);
?>
</body>
</html>
Author: Backrubber
John Dixon Technology Ltd
Go back to MySQL Tutorials home page
Go back to Tutorials home page
|
|
|