Select all data from a table and insert it to another table - php

I wanted to select all the data from one of my table and insert it to another table. I have this code but it wasn't working..This is what the phpMyadmin says "MySQL returned an empty result set (i.e. zero rows). (Query took 0.0010 seconds.)"
Here is my code:
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$query_select = "INSERT INTO pdf_table
SELECT * FROM $select_table";
$select_query = mysql_query($query_select,$connectDatabase);
}

Please ensure that both the tables have equal number of columns.
It is a good practice to use following way for inserting records with select query :-
INSERT INTO pdf_table (column_1, column_2) SELECT column_1, column_2 FROM $select_table

your sql query is like
INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;

The approach you are using INSERT INTO pdf_table SELECT * FROM $select_table will give you only single row inserted from 1st table to another table.
As per your requirement you want all the records from 1st table should get insert in your pdf_table
So i will like to suggest try the following approach
May be this is what you looking for
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$select_query = mysql_query( "select * from $select_table ",$connectDatabase);
while ($row = mysql_fetch_array($select_query))
{
mysql_query( "insert into pdf_table values($row['column1'],$row['column2'],...,$row['columns']) ",$connectDatabase);
}
}

try this one :
if(isset($_POST['select_table']))
{
$select_table = mysql_real_escape_string($_POST['select_table']);
$query_select = " Create Table pdf_table ( SELECT * FROM $select_table); ";
$select_query = mysql_query($query_select,$connectDatabase);
}
but, this query will create new table "pdf_table".

Related

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

Insert into if not exist MySQL

I'm using PostgreSQL to get data and i want to insert it into MySQL. I have a php script which allows me to get the data, check for repeated and then insert it into MySQL DB. Problem is that instead of inserting only the non existing data it inserts one random row and doesn't insert nothing else.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
the variables $episode_col and $episode_values get data from an array called $episode through implode:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
This is you code.
IF statements are used for comparisons, yours is just fetching the array and there's no condition inside your IF statement. You need to fix the statements to get the columns and their respective values.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
You can try to use WHERE EXISTS or WHERE NOT EXISTS too.
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
For more info: https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

Pass PDO result to another temproary table or insert to temp table

Hello ,
$sql = "select col1 , col2 from table where id=2"; // sometimes query larger
$q = $conn->prepare($sql);
$q->execute(array_values($v));
$q->setFetchMode(PDO::FETCH_BOTH);
while($r = $q->fetch())
{
echo " $r[$i]";
}
Code is Working Fine.
Now i want To save Query Result to Another Temporary Table.
i Dont know no. of columns generated in Query result. Each time Query is different so columns and data is different. So How store that Query result to another table.
You could let MySQL do that work for you, e.g. via
CREATE TEMPORARY TABLE new_tbl SELECT * FROM orig_tbl WHERE ...
see http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Select multiple rows from MySQL table

I have a session that contains an array and that array is filled with id's. What is the best way to select all the rows from a MySQL table that correspond to these id's?
So I need something like:
SELECT * FROM table WHERE id = $_SESSION['ids']
Obviously, this doesn't work, since $_SESSION['ids'] is an array.
SELECT *
FROM
table
WHERE
find_in_set(id, $_SESSION['ids'])>0
You can just use IN SQL operator.
In this case your query will look like
$sql = 'SELECT * FROM table WHERE id IN ("' . implode('","', $_SESSION['ids'] . '")';
This code will produse a query like following:
SELECT * FROM table WHERE id IN ("1", "2", "foo");
Hope it helps
HI Try This,
$var = $_SESSION['ids'];
and then fire your query as
$sql = SELECT * FROM table WHERE id = '$var';

Categories