Add database table from website - php

EDIT:Well I guess I should asked then before this question, would it be better to have a database full of tables(college names) that stores numbers than can be sorted in ascending order, or have a database with one table and select all the rows with the same "college name" and then sort the data from those rows after?
"
Is it possible to add a table in a database like...
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
...but call from a webpage instead of adding a table through mysql? So make a table in a database from code on my website?"

Yes you can send SQL queries through PHP.
Here is a resource that shows just what you're looking for I think
PHP MySQL Create Database and Tables
edit:
It depends on what you're doing, but I agree with the above comments that creating a table on page view is in most cases the wrong move.
If they all have the same basic structure I would put them all in the same table, and you can index the "college name" column. Reading from the database even with many many rows will still be quick, and if you decide to change something later you won't have to change X amount of tables.
You can also retrieve sorted results
SELECT * FROM Colleges WHERE name = 'University of Wisconsin' ORDER BY student_count ASC

Related

Select column(s) names based on user entry with a MYSQL query

Using PHP a secure user will enter a Ref (ex. NB093019) a query will be used to determine which PO(s) have that Ref and if they have any quantity. The issue is that we have 86 columns to check if that Ref is in and then once it finds what column it is in how to check the corresponding column that contains that quantity( the table cannot be edited).
I can make this work with 86 if else statements in PHP and then more if else statements inside of each PHP statement. I have no launching point once i do the initial query.
select 'remainder'as prefix, po, *comments,*GuideRef, *Qty
from remainder
where ('NB092419')IN (NWANTcomments,NWANTGuideRef,NWANTpreviouscomments,
NWANTpreviousGuideRef,NWANTprevious2comments,
NWANTprevious2GuideRef, BPrev2GuideRef,
BPrev2comments, BPrevGuideRef, BPrevcomments,
aGuideRef, Mcomments,MGuideRef,acomments,
MAGuideRef,BOGuideRef )
group by po
I have removed some of the in() information so it is not so long also the *comments, *GuideRef, *Qty would be decided by which one of the columns in the IN() statement returns information. Is this even possible
You could perhaps write an SQL that writes an SQL:
select REPLACE(
'SELECT ''{colstub}GuideRef'' as which, {colstub}Qty FROM remainder WHERE {colstub}Ref like ''%somevalue%'' UNION ALL',
'{colstub}',
REPLACE(column_name, 'GuideRef', '')
)
FROM information_schema.columns
WHERE table_name = 'remainder' and column_name LIKE '%Ref'
It works like "pull all the column names out of the info schema where the column name is like %guideref, replace guideref with nothing to get just the fragment of the column name that is varied: NWANTguideref -> NWANT, NWANTpreviousguideref -> NWANTprevious ... then uses this stub to form a query that gives a string depicting the column name, the qty from the quantity column, where the relevant guideref column is LIKE some value"
If you run this it will produce a result set like:
SELECT 'aGuideRef' as which, aQty FROM table WHERE aGuideRef LIKE '%lookingfor%' UNION ALL
SELECT 'bGuideRef' as which, bQty FROM table WHERE bGuideRef LIKE '%lookingfor% ...
So it's basically utputted a load of strings that are SQLs in themselves. It might need a bit of fine tuning, and hopefully all your columns are reliably and rigidly like xQty, xGuideRef, xComments triplets, but it essentially writes most the query for you
If you then copy the result set out of the results grid and paste it back into the query window, remove the last UNION ALL and run it, it will search the columns and tell you where it was found as well as the quantity
It's not too usable for a production system, but you could do the same in php- run the query, get the strings into another sql command, re-run it..
I would suggest you consider changing your table structure though:
prefix, qty, guideref, comments
You shouldn't have 86 columns that are the mostly same thing; you should have one column that is one of 86/3 different values then you can just query the guideref and the type. If this were an address table, I'm saying you **shouldn't* have HomeZipcode, WorkZipcode, UniversityZipcode, MomZipcode, DadZipcode.. and every time you want to store another kind of address you add more columns (BoyfriendZipcode, GirlfriendZipcode, Child1Zipcode...). Instead if you just had an "addresstype" column then you can store any number of different kinds of addresses without recompiling your app and changing your db schema
You can use this technique to re-shape the table - write an SQL that writes a bunch of UNION ALL sqls (without WHERE clauses), one of the columns should be the "recordtype" column (from colstub) and the other columns should just be "qty", "guide", "comments". Once you have your result set with the unions you can make a table to hold these 4 things, and then place INSERT INTO newtable at the head of the block of unions

Reordering MySQL

I have probably a very simple question.
I have a MySQL database called "alldata", which contains various variables. The first column called LogDateTime contains date and time. Now the thing is that I want the db to be sorted from the oldest to the newest - in other words by column 1.
I know how to do a MySQL query using ORDER BY Logdatetime etc. But what I would like to do is to reorder tha data in the actual database and save it ordered. Right now there are some dates a bit messed up. Then I would not have to use the ORDER BY statement in all my queries because the database would already be sorted.
Could anyone please just give me the SQL command I should use to reorder the entire database?
You cannot setup a relational database table to return results ordered by a specific column of your choosing. You need to use ORDER BY. You could work around this by using views.
The view definition would include an ORDER BY. You could select from the view and it would show results in your desired order.
CREATE OR REPLACE VIEW `mytable_view` AS SELECT * FROM `my_table` ORDER BY `my_date_column`
Then you can select the data:
SELECT * FROM `mytable_view`
Results are shown in desired order.

Search entire table for a keyword

I have a trivial question. Im using PHP+MySQL managing a huge DB
I want to search in a entire table a keyword I write in a input.
The problem is that the main table have +100 columns, so I had to write the php query manually
[...]
$sql="select *
from db
where ID LIKE '%".$q."%' or USER_ID LIKE '%".$q."%' or Phone_ID LIKE '%".$q."%' or
Fax_ID LIKE '%".$q."%' or email_ID LIKE '%".$q."%' or [...]
And this is a chaos when I modify a column, or add/remove...
Exist any other way to make this search? If not, I tought about create a separate PHP function, that obtains all column header names, and create an auto-fill function inside.
I tried to look for info with no success
https://stackoverflow.com/search?q=search+entire+table
Unfortunately there isnt any simple way to do this.
One option is to select all columns in table, fetch them as array and iterate over them and build your WHERE clause.
select column_name from information_schema.columns
where table_name = 'TableName'
This will make whole script slower, if you want to go this way i would recommend you to use some caching.
You could get the column info for the 'main table' using info from the information schema. Here are some methods for using MySQL. Here is how to do it using PHP.
You can do a SHOW COLUMNS on the table, then loop over the Field to get all the column names in the table, at least that way you don't have a hand-coded mess to deal with.

Completely arbitrary sort order in MySQL with PHP

I have a table in MySQL that I'm accessing from PHP. For example, let's have a table named THINGS:
things.ID - int primary key
things.name - varchar
things.owner_ID - int for joining with another table
My select statement to get what I need might look like:
SELECT * FROM things WHERE owner_ID = 99;
Pretty straightforward. Now, I'd like users to be able to specify a completely arbitrary order for the items returned from this query. The list will be displayed, they can then click an "up" or "down" button next to a row and have it moved up or down the list, or possibly a drag-and-drop operation to move it to anywhere else. I'd like this order to be saved in the database (same or other table). The custom order would be unique for the set of rows for each owner_ID.
I've searched for ways to provide this ordering without luck. I've thought of a few ways to implement this, but help me fill in the final option:
Add an INT column and set it's value to whatever I need to get rows
returned in my order. This presents the problem of scanning
row-by-row to find the insertion point, and possibly needing to
update the preceding/following rows sort column.
Having a "next" and "previous" column, implementing a linked list.
Once I find my place, I'll just have to update max 2 rows to insert
the row. But this requires scanning for the location from row #1.
Some SQL/relational DB trick I'm unaware of...
I'm looking for an answer to #3 because it may be out there, who knows. Plus, I'd like to offload as much as I can on the database.
From what I've read you need a new table containing the ordering of each user, say it's called *user_orderings*.
This table should contain the user ID, the position of the thing and the ID of the thing. The (user_id, thing_id) should be the PK. This way you need to update this table every time but you can get the things for a user in the order he/she wants using ORDER BY on the user_orderings table and joining it with the things table. It should work.
The simplest expression of an ordered list is: 3,1,2,4. We can store this as a string in the parent table; so if our table is photos with the foreign key profile_id, we'd place our photo order in profiles.photo_order. We can then consider this field in our order by clause by utilizing the find_in_set() function. This requires either two queries or a join. I use two queries but the join is more interesting, so here it is:
select photos.photo_id, photos.caption
from photos
join profiles on profiles.profile_id = photos.profile_id
where photos.profile_id = 1
order by find_in_set(photos.photo_id, profiles.photo_order);
Note that you would probably not want to use find_in_set() in a where clause due to performance implications, but in an order by clause, there are few enough results to make this fast.

Selecting datas from 10 (same formed) tables (create view)

Actually, I have no idea how does it looks like the question's title, is it exactly related to the issue or not, but I'm gonna try explain my problem:
I have a table named as AdvertClick (that stores the stats of each "Advert" by "AdvertID") and Advert table besides (as you guess the main table that stores my ad lists). So I need to store each advert click data (i.e. "Country","Browser","Language" etc.) in AdvertClick table. For example, the code is below getting top country data from AdvertClick table.
SELECT Count(_ac.ID) AS Click, _ac.Country
FROM `Advert` _a
LEFT JOIN `AdvertClick` _ac ON _ac.AdvertID = _a.ID
WHERE _a.UserID = $UserID
GROUP BY _ac.Country
ORDER BY Click DESC
LIMIT 1
But, I've replicated AdvertClick table as AdvertClick0, AdvertClick1 ... AdvertClick9, because it's (the unique stats table) was getting so heavy and slower. And now, I have 10 tables and all off them are same formed (meaning table colums). I'm just inserting every click data like this;
$TableName = "AdvertClick". $AdvertID % 10;
$SQL = "INSERT INTO ${TableName} ... VALUES (...)";
So, now I want to do same thing above but failing.
I've tried CREATE VIEW in very different ways like;
CREATE ALGORITHM = TEMPTABLE VIEW _tmp_ (colums...) SELECT x,y,z -> fail
CREATE VIEW _tmp_ (colums...) SELECT x,y,z JOIN AdvertClick0 _ac0 -> fail
etc...
Is anyone help me about this (really annoying) issue?
Thanks in advance...
hm... I think view would be appropriate for this kind of situation you should also have a good structured table to get the proper approach on this another approach I would do is to add another column that will identify what type of data are on that row for example:
table: advert
columns: name, country, type
the type will take any value you want or you may create another table and reference it from there as a foreign key to make it more flexible in that case you'll be having only 2 tables. To make if work as a view you can do it this way:
CREATE VIEW 'AdvertClick1' AS SELECT name, country FROM advert WHERE type = 1;
CREATE VIEW 'AdvertClick2' AS SELECT name, country FROM advert WHERE type = 2;
CREATE VIEW 'AdvertClick3' AS SELECT name, country FROM advert WHERE type = 3;
and so on and so forth. :)
i will propose something else entirely.
i think you should keep only one AdvertClick table - DO NOT create many of them and therefore create these other headaches. To get you answers will be even more difficult and even more slow.
Instead, if you are sure you have optimized your queries, you may choose to denormalize selectively to gather your common statistics.
for example:
create an ON INSERT trigger on the single AdvertClick table that increments the count value in a new AdvertClickByCountry table for the current Country. Also, create an ON DELETE trigger that decrements that count for the country.
Then your query above would be trivial - something like:
SELECT click_count, country
from AdvertClickByCountry
ORDER BY Click_count DESC
LIMIT 1

Categories