I'm following Model View Control method to create an application.
I'm trying to dynamically create tables upon a page is loaded. Here is the code for that.
In dashboard.php
<?php
require_once ("controller/db-config.php");
require_once ("controller/connectDB.php");
?>
In db-config.php
<?php
define('DB_NAME', 'learningcamp');
define('DB_USER', 'root');
define('DB_PASSWORD', ''); //Put your MySQL password here
define('DB_HOST', 'localhost');
?>
In connectDB.php
<?php
require_once ("controller/db-config.php");
require_once ("model/database.php");
// Create database connection
$databaseConnection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($databaseConnection->connect_errno)
{
die("Database selection failed: " . $databaseConnection->connect_error);
}
// Create tables if needed.
prep_DB_content();
?>
In database.php
<?php
require_once ("controller/db-config.php");
function prep_DB_content (){
global $databaseConnection;
create_tables($databaseConnection);
}
function create_tables($databaseConnection){
$query_fo_pages = "CREATE TABLE IF NOT EXISTS frontoffice (sl INT NOT NULL AUTO_INCREMENT, field VARCHAR(32) NOT NULL, description VARCHAR(800), flag INT NOT NULL)";
$databaseConnection->query($query_fo_pages);
}
?>
But somehow the tables are not created when I refresh the page dashboard.php
. Where did I go wrong?
The problem is that you defined an AUTO_INCREMENT column but not a primary key.
If you define any columns as auto increment, you must also make them key. Try this:
CREATE TABLE IF NOT EXISTS frontoffice(
sl INT NOT NULL AUTO_INCREMENT,
field VARCHAR(32) NOT NULL,
description VARCHAR(800),
flag INT NOT NULL,
PRIMARY KEY(sl))
EDIT
To answer your question in the comments, you would not have been required to declare a primary key if you had not used an auto_increment column.
You have an error in your SQL creation:
$query_fo_pages = "CREATE TABLE IF NOT EXISTS frontoffice (sl INT NOT NULL AUTO_INCREMENT PRIMARY KEY, field VARCHAR(32) NOT NULL, description VARCHAR(800), flag INT NOT NULL)";
Add PRIMARY KEY
on auto_increment
column.