In my php script, I used a sql query to create a table, but after creating the table every subsequent refresh will return an error message stating table is already created. I know its already created but how do I stop query from running a second time on refresh if its already ran?
php script:
<?php include_once ".env.php"; include_once "template.php"; html_top('School Database'); // open connection $conn = mysqli_connect(host,username,password,database_name); // verify connection if (!$conn) exit("<p class='error'>Connection Error: " . mysqli_connect_error() . "</p>"); // create table $sql = "create table students2 ( id int not null auto_increment, first varchar(20), last varchar(20), dob date, primary key (id))"; $create = mysqli_query($conn,$sql); if ($create) echo "Created"; else echo "Error creating table: " . mysqli_error($conn); html_bottom();
Advertisement
Answer
The DDL commands, such as create table
, should be in a separate file which is called only one time in the initialization step.
This is the formal way to be away from errors.
Another way that may help, but not efficient, is by using: CREATE TABLE IF NOT EXISTS Students2(....)
.
// create table $sql = "create table if not exists students2 ( id int not null auto_increment, first varchar(20), last varchar(20), dob date, primary key (id))";