JDT

 

FREE Downloads
Articles
Tutorials

 

Using PHP to Create a MySQL Database and Table


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



Earnings Tracker is John Dixon Technology's FREE accounting / bookkeeping software tool.

Aimed at contractors and freelancers, Earnings Tracker enables you to perform bookkeeping and accounting tasks, helping you to keep track of your company's revenue and spending.

The software is written in PHP and MySQL and is available to use for FREE online, or as a FREE download.

Earnings Tracker can also be used simply as a dividend, corporation tax, or VAT calculator.

Need free accounting software
 


JDT

Copyright Notice for John Dixon Technology Ltd

Privacy Statement

Terms & Conditions