How to Insert New Tables Into MySQL Using PHP
Web developers use the LAMP (Linux, Apache, MySQL and PHP) stack of technologies to build dynamic websites and Web applications. The PHP scripting language works well with MySQL, which is a database language. Combine the two to write code for your website that stores and retrieves user input. In PHP, write a MySQL query and run it in the "mysql_query()" function to build a new table. Once you build your table, use it to store multiple fields of data.
Instructions
-
-
1
Open a PHP file in Notepad where you want to add the code to insert new tables. Add a few blank lines for space and place a pair of PHP delimiter tags there. Inside those tags, start an "If" statement:
<?php
if () {
}
?>
-
2
Declare a new variable inside the parentheses of your "If" statement. Set the variable equal to the results of "mysql_connect()". Inside the "mysql_connect()" function, pass in "localhost" for the name of your Web server, plus your MySQL login name and password. Wrap the entire variable and its contents in a new pair of parentheses and put an exclamation mark in front:
<?php
if (!($db_conn = mysql_connect('localhost', 'username', 'password')) {
}
?>
-
-
3
Add an error message inside the "If" statement's curly braces, plus "exit()":
<?php
if (!($sql_conn = mysql_connect('localhost', 'username', 'password')) {
print("Sorry, but we failed to connect to the database!");
exit();
}
?>
-
4
Add this code to select the database and test for any errors:
if (!($db_conn = mysql_query('USE databasename', $sql_conn); {
print("Sorry, but we cannot connect to the database.");
exit();
}
This code goes between the PHP tags and after the code that connects to the database. Replace "databasename" with the name of the database with which you wish to work.
-
5
Write your MySQL query to build the table. In PHP, declare a variable and make its value equal to the MySQL query you want to use in order to build your query. This code goes between the PHP tags and after the connection code:
$query = 'CREATE table_name()';
-
6
Add fields to your table inside the MySQL query:
$query = 'CREATE table_name(
name varchar(100) default NULL,
ID int(11) auto_increment NOT NULL,
PRIMARY KEY(ID)
)';
Remember to create an ID field and give it an "auto_increment" setting. Use the ID field as the table's primary key, which will number every row of information in your table for easier access and better organization.
-
7
Add the "mysql_query()" function to the end of your code, above the closing PHP tag. Pass in the variable containing your MySQL query as the argument for this function. Write "or die(mysql_error());" after the function to handle errors:
mysql_query($query) or die(mysql_error());
-
1