Insert into if not exist MySQL - php

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

Related

How to assign two SELECT queries results to single array variable($row)?

There are two queries with same fields names but different tables. I want fetch both select query's results in same array variable $result. I tried few things but nothing working for me. May b my bad day.
two table, need to be fetch in same variable $result.
$sql1="SELECT city,phone,name from table1 where city='NY'";
$result = $conn->query($sql1);
$sql2="SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql2);
I don't want $result lost $sql1 data after assigning same variable ($result) to second query. Please help
You can use UNION and along with that table record identifier to identify table records differently.
$sql1 = "(SELECT city,phone,name, 't1' ttype from table1 where city='NY')
UNION (SELECT city,phone,name,'t2' ttype from table2 where city='NY')";
$result = $conn->query($sql1);
Note: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.
If you want duplicate records too, then use UNION ALL.
$sql1="SELECT city,phone,name from table1 where city='NY'
UNION
SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql1);

How to perform insert in one query?

Frame: MySQL server on localhost using XAMPP server.
I'm trying to insert all these fields in a particular table "tbl_labelled_images":
id_in_raw_image_table
image
label
gender
Out of them, image comes from another table named as "tbl_raw_image" and id_in_raw_image_table is the id of that image in table "tbl_raw_image".
Then label and gender are the inputs by the user taken on run time using radio buttons. But the problem is I cannot insert all these four attributes in a single query. Query just does not insert anything in the table if all of them are in the same query. I have tried following queries but none of them actually helped:
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`label`,`gender`,`image`, `id_in_raw_image_table`) '$label','$gender',
SELECT image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw";
$insert_exec = mysqli_query($conn, $query_insert);
And
$sql = "SELECT * FROM tbl_raw_image WHERE id IN
(SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query2="INSERT INTO tbl_labelled_image(image, label, id_in_raw_image_table) VALUES('$image','$label','$id'); ";
$rs = mysqli_query($conn2, $query2);
But none of them worked for me. As a work around I'm currently using a complex two step insertion as follows:
$sql = "SELECT * FROM tbl_raw_image WHERE id IN
(SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`image`, `id_in_raw_image_table`)
SELECT image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw;";
$insert_exec = mysqli_query($conn, $query_insert);
$labelled_id=mysqli_insert_id($conn);
$query_label = "UPDATE labelled_images.tbl_labelled_image SET
`label` = '$label', `gender` = '$gender' WHERE `id`=$labelled_id";
$label_insert_exec = mysqli_query($conn, $query_label);
$query_update_Is_labelled="UPDATE raw_images.tbl_raw_image SET `Is_labelled`= 1 WHERE id= $id_raw; ";
$update=mysqli_query($conn,$query_update_Is_labelled);
It works but it is far from ideal. So my question is that is there any way to perform this insert in one step? Or more generally what should be done when different fields of record to be inserted are from different sources?
You can try to use a static value in your MySQL select query SELECT '$label' as label,'$gender' as gender
complete query:
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`label`,`gender`,`image`, `id_in_raw_image_table`)
SELECT '$label' as label,'$gender' as gender, image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw
";
Edited: remove the VALUES() before the SELECT

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

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"

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

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".

Categories