Tutorials MySQL Creating New MySQL Tables with PHP

Creating New MySQL Tables with PHP

Hello and welcome to another tutorial at PHP Trainee. Today's tutorial will build upon last week's tutorial on MySQL. This time we will learn how to create a table in PHP. You can do this in phpMyAdmin but sometimes it might be faster to code it out.

Before you start

First, you need to have a MySQL database. After you have a MySQL database, you need to connect to it. You need to put the connection information above anything that has to with the database. You also need to know what kind of columns you want in your table. Read the MySQL Basics tutorial on how to do these things.

Create the table

After you have everything ready, coding the table is easy. The format is create table followed by the name and then the column details. You also have to state the different index values; the primary key is required to make a table. You will need to query the information after to make it activate the database.

// Table information
$sql = 'CREATE TABLE member
(
id int auto_increment,
name varchar(15) NOT NULL,
address varchar(15) NOT NULL,
phone int(10) NOT NULL,
email varchar(15) NOT NULL,
validated varchar(15) NOT NULL default"no",
PRIMARY KEY (id)
)';

// Execute query
$result = mysql_query($sql);
if ($result) {
  echo 'Successfully created table.';
} else {
  echo 'Error creating table. '.mysql_error();
}

Now what?

Now all you need to do is upload it to your server and run the script. After you finish running the script, remember to delete it. You don't want anybody accidentally stumbling onto the script, although they would probably get an error message saying table already exists but better safe than sorry.

And that's it for this tutorial. Try making your own tables and I'll show you how to manipulate the rows next time. See you all next week!

Posted by on . Category: MySQL


Comments

No comments posted yet

You need to register or login to post new comments.