Move Multiple Tables into One, with Addition of Extra Field Value - php

I have 31 separate tables (actually I have 365, but lets keep this simple) in a MySQL database, each containing data for a given day. The tables are (badly) named based on the day.
Example:
island01Aug07
island02Aug07
island03Aug07
island04Aug07
...
island31Aug07
I would like to combine all the tables into one master table:
island_08
It would be simple to use INSERT INTO but my problem is that the tables do not have a column to denote the day. It would have to be added into the destination table, and then I would need to populate that when moving/copying the tables over.
Suggestions, advice and solutions welcome.

CREATE TABLE island_08 (mydate DATE NOT NULL, field1 …)
INSERT
INTO island_08 (mydate, field1, field2)
SELECT '2007-07-01', field1, field2
FROM island01Aug07
UNION ALL
SELECT '2007-07-02', field1, field2
FROM island02Aug07
UNION ALL
…

As alternative option you can list all tables in to array like table_name=>mysql_date,
after that loop through and copy data from one table and insert in to another. After data was transferred successfully you can remove the table.
Here is example of getting list of tables and extracting date from it:
$prefix = 'island';
$lenght = strlen($prefix);
$result = $this->query("SHOW TABLES LIKE '{$prefix}%'");
$arrayDates = array();
if($db->num_rows($result))
{
while($v = $db->fetch_array($result))
{
$mysql_table = current($v);
$arrayDates[$mysql_table] = date('d-m-Y',strtotime(substr($mysql_table,0,$lenght)));
}
}
//Now you can walk through your array and copy data from one table tyo another and append you mysql value

Related

SELECT all tables from DB and query same column name in each one of them

I have several tables that are being imported by an external app. Their names are e.g Table_1, Table_296 and so on.
In each table, there is one column named Name.
My question is: How do I retrieve the names of all tables so I can put them into another query that will retrieve rows from each column Name?
Basically, I need to check for value and list a table (or tables) that contains it.
I can retrieve all tables names using the code below, but as far as I know, they can't all be SELECTED using a variable.
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME LIKE '%Table%' AND TABLE_SCHEMA='mydb'
I also know that the same column name cannot be selected if table names are not specified. Correct me if I'm wrong, please
First get all the table name then loop like below
$con = mysqli_connect("localhost","root","","databaseName");
$listdbtables = array_column(mysqli_fetch_all($con->query('SHOW TABLES FROM databaseName')),0);
foreach ($listdbtables as $key => $value) {
$sqlqry = "select Name from ".$value;
$nameResult = mysqli_query($con,$sqlqry);
while($nam = $nameResult->fetch_array()) {
echo($nam['Name']);
}
}

SUM values of specific column from all tables LIKE table_%

I need help to create an SQL query in order to SUM the values of specific column from all tables LIKE table_% as the tables will grow over time and this must cater for new table names based on the format below
Scheme Name: database_01
Table Names: tb_data_'YEAR'_'MONTH'
YEAR and MONTH are both values which range from all 12 months and years from 2011 to 2018.
Each Table contains a column called TOTAL_VALUE. I have a php script that triggers an SQL query to pull data from the database.
I would like to SUM the total of each tables TOTAL_VALUE column and save the value for my script below to push the array.
$sql = "SELECT TOTAL_VALUES FROM tb_data_2017_october";
$result = mysqli_query($conn, $sql);
$data = array(); while($enr = mysqli_fetch_assoc($result)){
$a = array($enr['TOTAL_VALUES']);
foreach ($a as $as){
echo "'".$as."', ";}
array_push($data, $as); }
I have been trying to alter the SQL with options such as:
SELECT id FROM table1
UNION
SELECT id FROM table2
UNION
SELECT id FROM table3
UNION
SELECT id FROM table4
However i need to cater for the ability to check all tables that are like tb_data_%
See this question for information about getting the list of tables: Get table names using SELECT statement in MySQL
You can get the list of tables in one query result, and then query each table. I'll rework your code slightly to give an example:
// Get the tables
$tables_sql = "SELECT table_name
FROM information_schema.tables
WHERE table_schema='<your DB>'
AND table_name LIKE 'tb_data%'";
$tables = mysqli_query($conn, $sql);
// Iterate over the tables
while($table = mysqli_fetch_assoc($tables)){
{
/*
* Your code
*/
// This query assumes that you can trust your table names not to to an SQL injection
$sql = "SELECT TOTAL_VALUES FROM " . $table['table_name'];
$result = mysqli_query($conn, $sql);
$data = array(); while($enr = mysqli_fetch_assoc($result)){
$a = array($enr['TOTAL_VALUES']);
foreach ($a as $as){
echo "'".$as."', ";
array_push($data, $as); }
}
You can do whatever you need once your have your list of tables. You can build one big union query (which would be more efficient than querying each table individually), or feed the tables to the MERGE engine, as in barmar's answer
Use the MERGE storage engine to create a virtual table that combines all the monthly tables.
CREATE TABLE tb_all_data (
...
) ENGINE=MERGE UNION=(tb_data_2017_october, tb_data_2017_november, ...);
List all the tables in the UNION= list, and update it whenever you create a new table.
Then you can just query from tb_all_data.
Try this- it will loop through all the tables with the pattern you want and create sums for you:
declare #table table (rowid int identity, name varchar(max))
insert #table
select name from sys.tables where name like '%yourname%'
declare #holding table (name varchar(max), sumvalue int)
declare #iterator int = 1
declare #tablename varchar(max)
while #iterator<=(select max(rowid) from #table)
begin
select #tablename=name from #table where rowid=#iterator
insert #holding
exec('select '+#tablename+' sum(TOTAL_VALUE)TOTAL_VALUE from '+#tablename+' group by +'+#tablename+'')
set #iterator=#iterator+1
end
select * from #holding

MySql Duplicate entries with auto updating context sensitive relations in PHP

Is there any possibility to duplicate specific entries by auto updating context sensitive relations?
Given a table 'table1' like:
My goal is to duplicate all entries with categoryId 42 while updating parentId if neccessary:
id is an auto incremented column and parentId is used to identify relations between the entries.
Currently I'm inserting them one by one, selecting the old data and managing the logic for the parentId in PHP.
//Thats simplified what I do ($conn is a Zend_Db_Adapter_Abstract)
$rows = $conn->fetchAll("SELECT * FROM table1 WHERE categoryId = 42 ORDER BY parentId ASC");
$newIds = [];
foreach($rows as $row){
if(array_key_exists($row['parentId'],$newIds))
$row['parentId'] = $newIds[$row['parentId']];
else
$row['parentId'] = null;
$conn->query("INSERT INTO table1 (parentId,info,categoryId) VALUES (?,?,?)",[$row['parentId'],$row['info'],$row['categoryId']]);
$newId = $conn->lastInsertId('table1');
$newIds[$row['id']] = $newId;
}
I'm stuck with this because I need the lastInsertedId of the new element to set the new parentId for the next one.
But I'm experiencing this to be pretty slow (in relation to one single query which contains the logic).
Is there any possibility to give a query some kind of incremental element sensitive logic? Or have you any suggestions on how to fasten this up?
Any help appreciated! :)
You are not showing any code. I guess you use mysqli_insert_id() to get the last inserted ID. Maybe you can do something with MAX(ID)+1.
Something like:
INSERT INTO table1
SELECT MAX(ID)+1,
info,
categoryId
FROM
table1
WHERE .............. -- the conditions to retreive the parent

Mysql Query In codeigniter

This is my mysql query
$acountry = 1;
$this->db->where_in('varcountry', $acountry);
$val = $this->db->get('tblagencies')->result();
In database table the varcountry filed is stored like this 1,2,3,4 its type is varchar.Each row in table have multiple countries that is the reason to use varchar datatype.
Here i want to select table rows which have $acountry value in the filed varcountry.
How can i do that?The above code is it correct?
You have choosen a wrong data type for storing a comma separated value 1,2,3,4 into varchar,
you should chose a data-type of set, or normalize into a separate table, like :-
create table country (id, name ...);
create table agencies_country ( agency_id, country_id);
insert into agencies_country (agency_id, country_id)
values (x,1), (x,2), (x,3), (x,4);
// meaning 1,2,3,4 = 4 rows
// grabbing result using inner join
Using set is easier, but common practice is to normalize the data (which require some understanding).
I don't like the active record in codeigniter,
is easy to use (not doubt with this),
but it dis-allowed lost of flexibility
Personally I like the construct my own query,
provided you have the understanding of the table schema (which you have to anyway)
use this query..
$search_field = array('varcountry'=>$acountry)
$result = $this->db->get_where('tblagencies' , $search_field );
but in codeignator you can use your own queries like
$sql = "select * from tblagencies where varcountry like '%acountry%'";
$result = $this->db->query($sql);

how to extract mysql data into json using php

i have retrieved mysql data from one table in json using the following script
$table_first = 'abc';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set = array();
$total_records = mysql_numrows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set[] = $link;
}
}
echo json_encode($set);
how can i retrieved data from two other tables in which there is a foreign key of this table in both of those tables. OR simply how can i retrieved data from 3 mysql tables in php.
I believe the best way to go here is using a JOIN or just something like this:
$sql = "SELECT
tabl1.*, table2.*, tabl3.* FROM table1, table2, table3
WHERE
table1.fk1 = table2.id AND
table1.fk2 = table2.id";
//Do the whole selection process...
If you make the queries separately, you'll be forcing 3 queries onto your database and will end in a performance hit that you dont need. So, the idea is load all the data from the DB using joins or similar that and then encode the results. Is faster and you'll leave the merging work to MySQL
Hope I can help
You can get all data firstly.
Then merge the data array.
Finally use json_encode to change the data format.
There is a foreign key of this table in both so you can use "join" to retrieve values from other tables.
Suppose that there are two tables as State(st_id,st_name) and City(ct_id,ct_name,state_id). Now, primary key are st_id & ct_id respectively of tables State & City.
Connection between this two table can be establish by joining State.st_id and City.state_id.
Now, coming to your problem to retrieve data from two table State & City, we can make sql query like following,
$sql="select s.*, c.* from State s, City c
where s.st_id=c.state_id ";
Using above query you can fetch data from database and convert into json format and can send it to android system. here is a good article http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/. i hope you like it.
I believe your code roughly will look like this:
$query = "SELECT
A.column1 AS First_1
A.column2 AS First_2
B.column2 AS Second
C.column3 AS Third
FROM table1 A, table2 B, table3 C
WHERE
A.fk1 = B.id AND
B.fk2 = C.id";
where a column is a relevant record you want to show. Meanwhile,
AS will act as a key name in JSON.

Categories