Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php stop sql query from running every time on refresh

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading