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
Related
I have two different Databases, names:
dbtest: Table 1
dbtest2: Table 2
I want to select all the data and new entries from dbtest Table 1 to dbtest2 Table 2.
I have tried this
$sqlfin = "INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1";
$resultfi = mysqli_query($db_conn, $sqlfin);
But no luck so far. How can I assure that new Records are insert into both table ? Any help would be appreciated?
lets try it in this format
INSERT INTO `dbtest2`.`Table2` SELECT * FROM `dbtest`.`Table1`
The following conditions hold for INSERT ... SELECT statements:
Specify IGNORE to ignore rows that would cause duplicate-key violations.
AUTO_INCREMENT columns work as usual.
To ensure that the binary log can be used to re-create the original tables, MySQL does not permit concurrent inserts for INSERT ... SELECT
statements (see Section 8.11.3, “Concurrent Inserts”).
To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table, provide a unique alias for each
table used in the SELECT part, and qualify column names in that
part with the appropriate alias.
INSERT ... SELECT Syntax
Create Trigger: for adding new entries
CREATE TRIGGER copy_record BEFORE INSERT ON dbtest.Table1
FOR EACH ROW
BEGIN
INSERT INTO dbtest2.Table2 (first_name, last_name) VALUES (new.first_name, new.last_name);
END
trigger_event indicates the kind of operation that activates the
trigger. These trigger_event values are permitted:
INSERT: The trigger activates whenever a new row is inserted into the table; for example, through INSERT, LOAD DATA, and REPLACE
statements.
UPDATE: The trigger activates whenever a row is modified; for example, through UPDATE statements.
DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. DROP TABLE
and TRUNCATE TABLE statements on the table do not activate this
trigger, because they do not use DELETE. Dropping a partition does not
activate DELETE triggers, either.
CREATE TRIGGER Syntax
Try this query for your desired task :
Query First (Create Table exactly same like in old database, if you have not):
CREATE TABLE dbtest2.Table2 LIKE dbtest.Table1;
Query Second (Insert all data to newly created table) :
INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1;
Your query looks correct but will fail if the 2 tables have a different structure. Specify the columns to avoid it like:
INSERT INTO dbtest2.Table2 (2_col_1, 2_col_2) SELECT 1_col_1, 1_col_2 FROM dbtest.Table1
With PDO (kind of alternative answer, I don't know much for Mysqli):
You could connect to Mysql with PDO without giving a database name when working with multiple ones (but this isn't mandatory), like:
$db = new PDO( "mysql:host=" . $host . ";", $user, $password, $options );
Then write the Database names, tables and columns like when making a JOIN (as you did): separated by a .
// an example ..
$useDb = $db->query("INSERT INTO db_1.table1 (value_1, value_2) SELECT value_3, value_4 FROM db_2.table2 WHERE db_2.table2.id = 5");
(example tested and working fine)
INSERT INTO dbtest2 (
id,
name,
status )
SELECT id,
name,
'1'
FROM dbtest
ORDER BY id ASC
You can use INSERT...SELECT syntax. Note that you can quote '1' directly in the SELECT part.
I have tested this query in phpmyadmin & it returns exactly what I'm looking for...it duplicates row1 & updates the title to DUPLICATE.
$sql = "CREATE TEMPORARY TABLE tmp
SELECT `unit_id`,
`title`,
`status_id`,
`category_id`,
`tags`,
`access_id`
FROM unit_genData
WHERE `unit_id`='1';
ALTER TABLE tmp
DROP COLUMN `unit_id`;
UPDATE tmp
SET `title` = 'DUPLICATE';
INSERT INTO unit_genData
SELECT 0,tmp.*
FROM tmp;
DROP TABLE tmp;";
Then I go and add it to a php page, and...
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ALTER TABLE tmp DROP COLUMNunit_id; UPDATE tmp ' at line 10
Why am I getting this error?
use mysqli_multi_query() for executing multiple queries.
$sql = "CREATE TEMPORARY TABLE tmp
SELECT `unit_id`,
`title`,
`status_id`,
`category_id`,
`tags`,
`access_id`
FROM unit_genData
WHERE `unit_id`='1';
ALTER TABLE tmp
DROP COLUMN `unit_id`;
UPDATE tmp
SET `title` = 'DUPLICATE';
INSERT INTO unit_genData
SELECT 0,tmp.*
FROM tmp;
DROP TABLE tmp;";
$mysqli->multi_query($sql);
By default, PHP disables multiple statements in a single query.
Either run the two statements separately, or you can use mysql_multi_query.
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
(Question doesn't specify which MySQL interface is used.)
Note that if your code is subject to SQL Injection vulnerabilities, then enabling multiple statements per query can throw open the door to a whole boatload of nefariousness... ala Little Bobby Tables http://xkcd.com/327/.
If you're for some reason using mysql functions pass CLIENT_MULTI_STATEMENTS as mysql_connect's 5th parameter to allow multiple statements in your queries.
More info here.
I've finally gotten my queries ready to insert into code but now I'm getting an error when running the whole query. I believe it has to do with the drop table function. I originally had them inline and then read that I should remove it and add at the beginning of the query like so:
$query = $this->db->query("DROP TABLE IF EXISTS resultx;");
$query = $this->db->query("DROP TABLE IF EXISTS resulty;");
$query = $this->db->query("
CREATE TEMPORARY TABLE resultx AS
select *, CONCAT(Credit,'_',OrderStat) as consol from (..........
I am creating two temp tables and then joining them in the last query. I am not sure how to put that second DROP temp table back into the full query or if that's even the right way to go.
The error that I'm getting is:
A Database Error Occurred
Error Number: 1064
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 'CREATE TEMPORARY TABLE resulty AS select packetDeet,Sales,SaleDate, UserID,Lead' at line 15
Query:
CREATE TEMPORARY TABLE resultx AS
select
*,
CONCAT(Credit,'_',OrderStat) as consol
FROM
( select
packetDetailsId, GROUP_CONCAT(Credit) AS Credit,
GROUP_CONCAT(AccountNum) AS AccountNum,
GROUP_CONCAT(OrderStat) AS OrderStat
FROM
( SELECT
pd_extrafields.packetDetailsId,
CASE WHEN
pd_extrafields.ex_title LIKE ('%Credit%')
THEN pd_extrafields.ex_value
ELSE NULL
END as Credit,
CASE WHEN
pd_extrafields.ex_title LIKE ('%Account%')
THEN pd_extrafields.ex_value
ELSE NULL
END as AccountNum,
CASE WHEN
pd_extrafields.ex_title LIKE ('%Existing%')
THEN pd_extrafields.ex_value
ELSE NULL
END as OrderStat
FROM pd_extrafields
) AS myalias
GROUP BY packetDetailsId
)as TempTab;
CREATE TEMPORARY TABLE resulty AS select packetDeet,Sales,SaleDate, .........
Please let me know if this makes sense or I need to update question with more information.
If you are trying to execute both queries in one call to $this->db->query() the problem is probably that your database library does not permit multiple queries.
To see if that is the problem, you should split them up in two separate queries.
i have any sql command for create backup from table's fields and i'm using this bewlow command in phpmyadmin:
SQL:
CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM sale_khomsi;
UPDATE tmptable_1 SET id= NULL , faal= 1;
INSERT INTO sale_khomsi SELECT * FROM tmptable_1;
DROP TEMPORARY TABLE IF EXISTS tmptable_1;
this work correctly but after runing this command into php code such az:
PHP:
$reslut=mysql_query("CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM sale_khomsi;
UPDATE tmptable_1 SET id= NULL , faal= 1;
INSERT INTO sale_khomsi SELECT * FROM tmptable_1;
DROP TEMPORARY TABLE IF EXISTS tmptable_1;");
not working .
result of MYSQL into PHPMYADMIN:
CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM sale_khomsi;# 4 rows affected.
UPDATE tmptable_1 SET id= NULL , faal= 1;# 4 rows affected.
INSERT INTO sale_khomsi SELECT * FROM tmptable_1;# 4 rows affected.
DROP TEMPORARY TABLE IF EXISTS tmptable_1;# MySQL returned an empty result set (i.e. zero rows).
There is no option for executing multi-query in mysql. But if you go for mysqli it is there.
mysqli_multi_query()
But if want to use mysql only mean you can go for procedure for these kind of things.
phpMyAdmin uses ; as a delimiter between calls to the database. Therefore entering that string in phpMyAdmin will cause 4 queries to run, not one massive query as you have. You need to break it down.
$result = mysql_query("CREATE TEMPORARY TABLE tmptable_1 SELECT * FROM sale_khomsi");
$result = mysql_query("UPDATE tmptable_1 SET id= NULL , faal= 1");
$result = mysql_query("INSERT INTO sale_khomsi SELECT * FROM tmptable_1");
$result = mysql_query("DROP TEMPORARY TABLE IF EXISTS tmptable_1");
That should give you the desired result. Of course you need to check the outcome of result to make sure the query was successful.
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?)