insert into table as select * from table does not work - php

This SQL statement is used in PHP:
Insert into Table from AS Select * from Tabl1 where id='5'
Any clues to why it is not inserting values from Table1 to Table? User executes this statement to create a copy.

Remove the "FROM AS" and it should work. See http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html

Remove from as:
Insert into Table (Select * from Tabl1 where id='5')
(and BTW why '5' and not just 5? Is id actually a string value?)

Related

Getting inserted row on if/-then-else statement

When I use an if-then-else to check if a record exists then call the last insert using $pdocon->lastInsertId() it does not return the inserted row. For example:
if exists(
SELECT first_name FROM `my_table`
WHERE first_name = 'adam'
)
then
SELECT * FROM `my_table` WHERE first_name = 'adam'
else
INSERT INTO my_table
(first_name)
values
('adam')
END IF;
This (simplified) code checks to see if a record exists. If it does exist, it grabs the info. If it does not exist it inserts it. That part all works fine, the problem comes in when I try to get the inserted ID from a name the doesn't exist (returns a 0 as lastInsertId).
Is there a practical way around this?
If you want to ensure that names are not duplicated, then you should define a unique index or constraint on the column:
alter table t add unique constraint unq_my_table_first_name unique (first_name);
Then you can use the following trick to get the correct id using last_insert_id():
insert into mytable (first_name)
values ('Adam')
on duplicate key update id = last_insert_id(id);
You can then use:
select last_insert_id()
to get the last insert id regardless of whether the statement was an update or insert.
Here is a db<>fiddle.
First the question should not have PHP tag because PHP doesn't have if-then-else conditional statement that's a Visual Basic conditional statement. Nevertheless an if-else can handle this with you using the right SQL query, SQL already provides a query that solves the issue above i.e. to check for the existence of a record and that should help.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
To anyone looking in the future, another user posted the answer but then deleted it. The correct way to accomplish this is:
if exists(
SELECT first_name FROM `my_table`
WHERE first_name = 'adam'
)
then
SELECT * FROM `my_table` WHERE first_name = 'adam'
else
INSERT INTO my_table
(first_name)
values
('adam');
SELECT LAST_INSERT_ID() as inserted;
END IF;

Insert the existing value and sort it from another table

Insert the existing value and sort it from another table
I'm trying to call data from table A and but table A is sorted from table B.
Detail: Table A stores "ID" and table B stores numbers, I want to sort table A based on the numbers in table B.
I tried the code below but it didn't work
$result = $db->Query("INSERT INTO `session`(`id`)VALUES('".$id['tableA']."' ON SELECT * FROM `tableB` WHERE `number`<'500' )") ;
After I run the code does not save to the database.
I hope the experts can solve my problem. thank you
remove the ON in your syntax as the right query is:
INSERT INTO [table] SELECT * FROM [anothertable]
as explained in detail in MySQL documentation
As for your situation, the right query should be:
INSERT INTO `session`(`id`) SELECT `id` FROM `tableB` WHERE `number` < 500;

Duplicate records in MySQL. EXISTS check for the same data not working properly?

SELECT EXISTS
(SELECT * FROM table WHERE deleted_at IS NULL and the_date = '$the_date' AND company_name = '$company_name' AND purchase_country = '$p_country' AND lot = '$lot_no') AS numofrecords")
What is wrong with this mysql query?
It is still allowing duplicates inserts (1 out of 1000 records). Around 100 users making entries, so the traffic is not that big, I assume. I do not have access to the database metrics, so I can not be sure.
The EXISTS condition is use in a WHERE clause. In your case, the first select doesn't specify the table and the condition.
One example:
SELECT *
FROM customers
WHERE EXISTS (SELECT *
FROM order_details
WHERE customers.customer_id = order_details.customer_id);
Try to put your statement like this, and if it returns the data duplicated, just use a DISTINCT. (SELECT DISCTINCT * .....)
Another approach for you :
INSERT INTO your_table VALUES (SELECT * FROM table GROUP BY your_column_want_to_dupplicate);
The answer from #Nick gave the clues to solve the issue. Separated EXIST check and INSERT was not the best way. Two users were actually able to do INSERT, if one got 0. A single statement query with INSERT ... ON DUPLICATE KEY UPDATE... was the way to go.

Laravel DB::unprepared

Just the 1st and 2nd statment works. When it comes to the third and fourth one, no results can be seen on the database.
I checked the logs (centos x64) for both php and mariadb but no errors recorded. No exceptions thrown too in try/catch blocks.
DB::unprepared('
CREATE TABLE clone1 LIKE table1;
INSERT clone1 SELECT * FROM table1
WHERE field LIKE "'.$value.'%";
CREATE TABLE clone2 LIKE table2;
INSERT clone2 SELECT * FROM table2;
WHERE field LIKE "'.$value.'%";
CREATE TABLE clone3 LIKE table3;
INSERT clone3 SELECT * FROM table3;
WHERE field LIKE "'.$value.'%";
CREATE TABLE clone4 LIKE table4;
INSERT clone4 SELECT * FROM table4;
WHERE field LIKE "'.$value.'%";
');
Any ideas? Thanks in advance.
Easy answer: I removed the commas from the end of the insert rows, which was caused the query to stop before where statements.

execute multiple query with temp table in php

I have the following query, to copy a row within a table and alter a few columns.
CREATE TEMPORARY TABLE temp_table AS
SELECT *
FROM table1
WHERE offertecode = '1c12a23453453458e492230df420972';
UPDATE temp_table
SET offertecode = '82a24c7da2342423424351804ab043',
id = NULL,
reference = '[COPY] subject';
INSERT INTO table1
SELECT *
FROM temp_table;
DROP TEMPORARY TABLE temp_table;
This works perfectly fine in phpmyadmin, but I cant get it to work from within PHP, I get an error:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax
to use near 'UPDATE temp_table SET offertecode = '82a24c7da2342423424351804ab043',
id = ' at line 5
Can anyone help me on how to execute this query in PHP?
PHP code:
$mysqli->query("CREATE TEMPORARY TABLE temp_table AS
SELECT *
FROM table1
WHERE offertecode = '1c12a23453453458e492230df420972';
UPDATE temp_table
SET offertecode = '82a24c7da2342423424351804ab043',
id = NULL,
reference = '[COPY] subject';
INSERT INTO table1
SELECT *
FROM temp_table;
DROP TEMPORARY TABLE temp_table;");
Thanks!
This doesn't address the mysqli problem (which is having four statements in a single query). You should run those separately. But, you don't need four statements. Just do:
insert into table1(offertecode, id, reference, <rest of columns>)
select '82a24c7da2342423424351804ab043' as offertecode, NULL as id, '[COPY] subject' as reference,
<rest of columns>
from table1
where offertecode = '1c12a23453453458e492230df420972';
An insert . . . select statement can refer to the same table in both parts. Even in MySQL.
You need to use $mysqli->multi_query. The basic answer is you cannot run multiple queries using $mysqli->query. The syntax error is due to a second query trying to to be run under $mysqli->query which only allows one main query. That query can contain sub or nested queries, but only one main query. To run multiple queries you have to use $mysqli->multi_query

Categories