PHP offers various functions for developers to interact with MySQL databases, among which mysql_query is commonly used to execute SQL statements, including table creation. This article explains how to use PHP code to create a MySQL table named tutorials_tbl through an example.
<html> <head> <title>Creating MySQL Tables</title> </head> <body> <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(!$conn) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully<br />'; $sql = "CREATE TABLE tutorials_tbl( " ."tutorial_id INT NOT NULL AUTO_INCREMENT, " ."tutorial_title VARCHAR(100) NOT NULL, " ."tutorial_author VARCHAR(40) NOT NULL, " ."submission_date DATE, " ."PRIMARY KEY ( tutorial_id )); "; mysql_select_db('TUTORIALS'); $retval = mysql_query($sql, $conn); if(!$retval) { die('Could not create table: ' . mysql_error()); } echo "Table created successfully<br />"; mysql_close($conn); ?> </body> </html>
The code starts by connecting to the MySQL server using mysql_connect, then selects the target database with mysql_select_db. The SQL statement defines the structure of the table, including fields, data types, and the primary key. Finally, mysql_query executes the SQL to create the table.
If the connection or table creation fails, the script outputs an error and stops execution. Upon success, it displays a confirmation message.
This example demonstrates the basic process of creating a MySQL table using a PHP script. Once you understand this method, you can expand the table structure and functionality to suit more complex database operations.
Related Tags:
MySQL