简体   繁体   中英

Sorting fetched tables names from databse. Mysql PHP

I need to get all back up tables that are associated with their base table. For example, table_name yields table_name_backup1, table_name_backup2 ..etc. The reason for doing this is because I don't want to get backup tables names manually, there could be dozens of them and they are named based on game week and date and therefore their names cannot be predicted.

The result I get after executing this statement if $tbl = 'ranking' for example:

...

function getTables($tbl){
  $query = "SHOW TABLES LIKE '" . $tbl . "_gw%' ORDER BY ";

Result

 [0] => ranking_gw0_231012
    [1] => ranking_gw10_231012
    [2] => ranking_gw11_231012
    [3] => ranking_gw1_231012
    [4] => ranking_gw2_231012
    [5] => ranking_gw3_231012
    [6] => ranking_gw4_231012
    [7] => ranking_gw5_231012
    [8] => ranking_gw6_231012
    [9] => ranking_gw7_231012
    [10] => ranking_gw8_231012
    [11] => ranking_gw9_231012
    [12] => ranking       // I insert this manually before return statement. 

Everything is ok except that the order is not correct for tables with more than 9 backups, since table gw10 appears in index 1 and therefore, shows wrong data order when I submit their values.

I have been thinking to make a function that will extract the number in gwx and re sort the whole thing, but i think there must be a simpler way.

So, how could I show these tables in their correct order?

BTW, when i view my db in MYSQLYOG, they appear in that same exact order, while in my phpmyadmin they are shown in correct order, gw11 is shown the last one. There is a possibility to have two tables with same gwx value, eg ranking_gw0_080812 and ranking_gw0_101012

You should do something like:

select table_name from information_schema.tables 
  where table_schema="yourDbName" and table_name like '" . $tbl . "_gw%' 
  order by create_time;

Since you need only the tables that match a specific pattern, ordered by the time of creation.

You can try a different approach where ordering is possible:

SELECT table_name 
FROM information_schema.tables 
WHERE table_schema='your_database_name'  
ORDER BY table_name ASC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM