Home > Enterprise >  php stop sql query from running every time on refresh
php stop sql query from running every time on refresh

Time:11-13

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

CodePudding user response:

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

CodePudding user response:

It is a logical error when using create or alter tables commands more than one, or when using them in the pages or functions that frequently used or refreshed. In your case there are many solutions, but the perfect solution is to separate the creation commands from other code.

Or you can use the (if exists ) when creating any table as guys answered you.

  • Related