user6307157
user6307157

Reputation: 23

Create Table Just Once?

I have a few nagging questions about creating tables:

  1. If I use PHP to create a MySQL function to create a table, I know it works the first time (to create a database for usernames and passwords) but what about the following times when the database sees the code to "create table". It seems to ignore it on my virtual server, but I was just wondering if this is wrong. Does it keep trying to create a new table each time? Is it okay to leave that code in?

  2. Another question I have is, let's say I go into PHPMyAdmin and add a column called "role" (to define the user's role). The sign in page will crash since I added a column in PHPMyAdmin, but if add the column using PHP/MySQL it is perfectly fine. Why is that?

Upvotes: 1

Views: 1281

Answers (3)

rhazen
rhazen

Reputation: 173

1.) It depends on the purpose of the table.

If you need to create tables dynamically then your code should check each time if the table exists:

CREATE TABLE IF NOT EXISTS 'yourTable'

However if you create the table only ones, there is no need to check for existence over and over again, so the code to create these table(s) should execute one time only.

2.) You need to update the function that does the insert or read after adding a column via PHPMyAdmin. It's difficult to answer your second question as I don't know what your functions do.

Upvotes: 1

Alok Patel
Alok Patel

Reputation: 8022

CREATE TABLE is executed each time you run the function.
It's better to replace the syntax with CREATE TABLE IF NOT EXISTS.

The keywords IF NOT EXISTS prevent an error from occurring if the table exists.

If you does not add IF NOT EXISTS it will throw the error.

Reference: http://dev.mysql.com/doc/refman/5.7/en/create-table.html


Please post your code in question to help you with second query.

Upvotes: 1

deceze
deceze

Reputation: 522412

  1. Do not keep your CREATE TABLE ... statements in your PHP code so that they execute every single time on every single page load. It's unnecessary and error prone. The statements are not being ignored, very likely they are run and are producing errors, and you're simply not checking for errors.

    Database creation is a deployment step, meaning when you upload your code to your server, that's the one and only time when you create or modify databases. There are entire toolchains available around managing this process; learn something about automated deployment processes and database schema versioning at some point.

  2. No idea without seeing your code and the exact error message.

Upvotes: 0

Related Questions