To Create a new Table in a MySqli Database you will have to be sure of the following. #mysql

  1. You Created A Database
  2. You Granted Privileges to the database
  3. Created a config.php file to access the database
If you have those 3 steps done you will now be able to create a new table in a MySqli Database. Here is the code that you will need to accomplish this the object oriented way. Create a file and call it make-table.php. Insert the following code into the file and it will make a table in your database called "about". Within that table there will be 3 rows.
  1. An id row
  2. A Description row
  3. A timestamp
Imagine the database like this. You are creating the top row and preparing the database to insert values into it.
id description timestamp
values values values
Here is the code to create this table.
<?php include('config.php');
// sql to create table
$sql = "CREATE TABLE about(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
description VARCHAR(250) NOT NULL,
reg_date TIMESTAMP
)";

if ($con->query($sql) === TRUE) {
echo "Table about created successfully";
} else {
echo "Error creating table: " . $con->error;
}

$con->close();
?>
If you are having trouble you may want to go back and check that you have access to the database and that you correctly set all the usernames and passwords correctly. Also make sure that you granted privileges to the user to access the database.

Create Multiple Tables in One Script php mysqli

include('config.php');
$sql = "CREATE TABLE IF NOT EXISTS `mytable` (
  `id` int(6) unsigned NOT NULL AUTO_INCREMENT,
  `table1` varchar(250) NOT NULL,
  `table2` varchar(250) NOT NULL,
  `table3` varchar(250) NOT NULL,
  `table4` varchar(250) NOT NULL,
  `table5` varchar(250) NOT NULL,
  `table6` varchar(250) NOT NULL,
  `table7` varchar(250) NOT NULL,
  `table8` varchar(250) NOT NULL,
  `table9` int(9) NOT NULL,
  `table10` int(9) NOT NULL,
  `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
";
if ($con->query($sql) === TRUE) {
echo "Table fantasyplayers created successfully";
} else {
echo "Error creating table: " . $con->error;
}

File Paths

In the example above we have the config file right in line with the make-table.php file. That means they are in the SAME folder. If you have it in another folder make sure that you reflect that when you put your includes filename at the top of the make-table.php file.


Sign Up To Comment