Checking if MySQL Tables Exist and if not create them - php

What would be the best way to check if tables exist in a MySQL DB? I was looking at a few code examples and have seen it done a couple of ways.
What I am trying to do is create tables like tag_tagnamehere so each tag has their own table with a link to the post/page ID.
So what I'm thinking is when people inset a list of TAGS I would loop through them and if the table is not found, create it and make and entry to that post/page ID.

CREATE TABLE IF NOT EXISTS
Maybe I didn't understand your design/table structure, although each tag shouldn't reside in its own table. You should have a table of tags, and a normalised scenario where other tables (if need be) define other tag attributes

Create table has that built in.
Create table Foo if not exists
But you probably shouldn't do this. Note how its done here with a PostTag table

CREATE TABLE IF NOT EXISTS <table_name>...

How about directly from a MySQL Query?
CREATE TABLE someTable IF NOT EXISTS

Related

Create table if not exists is costy?

I`m creating a simple data mapping system with PHP, PDO and Mysql.
One of its premises is to map arrays to entities by creating tertiary tables (not sure if the name is correct).
So, when I map an Array, I create the table with a works-for-all statement that uses the class name and method name passed, something like this:
"create table if not exists ".$tablename." (id_".$firstName." int unsigned not null, ".$secondName." ".$type.", constraint fk_".$tablename." foreign key (id_".$firstName.") references ".$firstName."(id) ".$secondReference.");"
The code is not the problem here.
What I wanted to know is if its a bad idea to TRY to create a table (if not exists) in every iteration (it does only create it for real in the first iteration of each element).
EDIT (explaining): As stated, creating inumerous tables is not the worry (wont happen), for this process is automated according to the classes (models) I`m using. The worry is if it is too costy memory and trafic-wise to check if the table exists at every iteration (this way for each item I would access the database twice, once for checking if the table exists and then again for inserting the new element into the table).
Another option would be to check if the table exists trough a select statement first, but it doesn`t seem much better.
One important information is that these methods used for mapping will olny be accessed through the objects DAO referencing each entity.
Edit: The link for the GitHub with the project is https://github.com/Sirsirious/SPDMap
to me it doesn't sound ideal to create a table each time. Might be better to reuse the same table (with an additional column as identifier between your current 'tables'
if you do create the table, don't see anything wrong with create table if not exist. this is a safe and good programming
I'd also consider using temp tables for this thing. if you create the table each time, it sounds like they are one-time usage as well. so if you don't need the data forever, temp can be a good way to go

Create auto_incremented table name?

I am wondering how I could, using PHP and mysql, create a table with a unique name every time.
So example if i click submit, a table will be created that is named "1".
then if i do it again another table is added and it is named "2"
I searched around but could only find answers to how to auto_increment the columns inside the table so I hoped it would be the same code, I tried this:
mysql_query("CREATE TABLE INT NOT NULL AUTO_INCREMENT PRIMARY KEY(TestColumn CHAR(30))");
It did not work.
So how do you create an auto_incremented table ???
Create a simple file which store a serial number. Then when your script creates a table, you increment the counter in the file with one. Next time, you read the number and use that for the table name. Naturally, you could do this in a table or a flat file.
Just for knowing which tables exist, and what they are for, you'd best create one master table storing not just the latest, but all tables created.
I am lost as to why you would want to do this.. I see no good reason for wanting this.
Create a table of tables and store the number or the number name in that table. Then you can look up MAX number there.
First at all, this function don't exist in PHP or in MySQL. Or maybe I don't know it.
There is 2 solutions to your problem :
Solution number 1 :
As AlanChavez said, you can use this request :
CREATE TABLE IF NOT EXIST ....
But, if you have to create 1000000000 table (it's an example), it will not be optimized.
Solution number 2 :
You can create a table with a single row, where is stored the last name used for your table.
I don't know if it's really optimized, but I think it can work.
I will never recommend to name a database table just with a digit. To keep track of number of click / page-load you can use file, session or another table.

Create table for each id existent in another table

I was wondering if there is a way to create a MySQL table for each ID that exists in another table. I think that would be fairly easy doing it with PHP, but I'm not sure if that can be done with MySQL.
So for instance I have a table called users which has an X amount of columns. One column is the IDs column. So I would like to iterate through that column and grab the IDs and create for each of those IDs a new table which will have the name of "user_specific_id_ " + ID. So for the ID 1 the name of the newly created table would be user_specific_id_1.
Could the above be done just with MySQL, or is it necessary to use PHP ? And if I need to use PHP what would be the approach ?
I'm not familiar with a pure MySQL way. Using PHP you'll select all id's from your table, and then in a foreach loop issue a CREATE TABLE user_specific_id + $id query
That being said, creating a separate table for each user doesn't sound like the correct way of handling a DB.
This sounds like an awfully bad idea.
It is a bad idea because you cannot decently JOIN the tables using mysql.
Instead of a table for each user, consider having a table with a multi-column primary key for all users.
You can, of course do what you described with PHP, for example using PDO.

how create VIEW for local work, without update in TABLE?

How to create a VIEW that it does not update data in a TABLE? For example, I want to delete rows only in the VIEW and the TABLE, on which the established VIEW, that there should be no deletions ... how to do it?
like this does not work ...
"CREATE OR REPLACE VIEW $prefix"
. "Test_View AS SELECT * FROM Table1 WITH LOCAL CHECK OPTION";
it is rather to check ... please, help!
If you want to have a VIEW where you can't update/delete data, add a distinct (e.g. on a unique key, where it essentially doesn't have an effect).
See the MySQL Ref on updatable views:
There are also certain other constructs that make a view nonupdatable. To be more specific, a view is not updatable if it contains any of the following:
Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth)
DISTINCT
GROUP BY
...
Deleting Rows from a view will delete them from the corresponding table.
You really should alter your view definition to exclude the rows you do not want.
You don't want to be using a view for this. You would need a second table that is updated by a on insert / on update trigger, if you want the table to exist permanently. Otherwise just create a temporary table for each query by using INSERT..SELECT statements.

Inserting an entry in multiple tables in an sql database

I'm creating a game in actionscript that requires the use of an external database to store user details and scores.
This database will contain multiple tables, currently there are two.
My first table contains the headers - ID, email, username, password.
My second table contains the headers - ID, lvl1Score, lvl2Score, lvl3Score.
In my game, when a new user is created it creates an entry in the first table with the ID auto-incrementing.
My question is - Is there anyway to automatically create an entry in my second table with its default values and the same ID when I add to my first table?
I've read about joins, but everything i've read just talks about looking up data over multiple tables.
Also, is my table structure correct in the sence that the ID value can be used using the JOIN keywork to look up an entry from both tables.
I would suggest you to go for triggers.
create or replace trigger trigger_name after
insert on table1
for each row
begin
insert into table2 values(new.id,"value for lvl2score","value for lvl3score");
end
Something like this.
If the tables truly have a one-to-one relation, I would recommend that you simply make one table having all the fields.
Or did you mean this should store multiple scores for each individual user? In this case, you should not insert a default record for the user. Instead, the score.ID field should instead reference user.ID and allow duplicates.
I suggest you to use triggers and for more flexibility create a many-many relationship between "user" and "level", so you will end up with 3 tables:
user
level
user_level (this will contain the foreign keys: user_id, level_id)

Categories