i need to insert values into two different table with single query - php

How do I join these two queries and execute them as a single query to insert values in two tables:
$sql = mysql_real_escape_string('INSERT INTO admin_export(datetime, product_name, item_code,quantity,subject,export_no) VALUES').implode(',', $row_data);
$sql2 = "insert into `itflower_exportno` (admin_exportno) values('$exportno1')";

You need to separate your two INSERT statements with a semicolon into the single variable.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
You can however use transactions as following example.
BEGIN;
INSERT INTO users (username, password)
VALUES('test', 'test');
INSERT INTO profiles (userid, bio, homepage)
VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com');
COMMIT;

What you have in the code are two different inserts.
MySQL doesn't allow for multiple inserts to be run in the same query so you will have to do one first and then the other.
However you can insert multiple rows in the same table in just one query, basically you are restricted to do all the insert you want in one table at a time.

You can't do this.
If you want to do it because you are afraid of the integrity of the data, use transaction .
Second, use suitable transaction isolation level, to ensure that data are reading correctly.

Related

SQL, how to get the automated ID from the previous INSERT?

I am using PHP and SQL and trying to insert user data into two tables upon registration. First in the user_table and second into the character_table. I'm using an automatically generating user_id to link the tables and need to get the value of the user_id from the first INSERT (into user_table) then add it to a column in the character_table.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Run your statements seperately. You run your insertion into your user_table, then grab the id then run your insertion into your character_table
You can grab the id using mysql_insert_id after running the insert. Note that on the php webpage detailing the mysql_insert_id function that it is deprecated as is all mysql* functions. Which leads to...
For the love of everything holy don't concatenate your variables directly to your INSERT statement. Switch to mysqli* functions or PDO if you haven't already and use prepared statements (parameterizing the query). If you build an application using mysql it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.
If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id() (or PDO::lastInsertID()) function

SQL Update a whole table with new data

I am running a query every 15 minutes to retrieve new data from an API and store this data in my database.
So every 15 minutes I would like to store the new data in the table and get rid of the all old data in that table.
I am currently using the following method:
$sql = "DELETE FROM self_user_follower
INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, last_updated)
VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id, :query_last_updated)";
But it gives me the following error:
Array
(
[0] => 42000
[1] => 1064
[2] => 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 'INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, l' at line 2
)
query_error
Is this the best way to do it or is there a nicer and cleaner way to do this?
If you want to put two SQL queries into one statement string, you have to
separate them with a semi-colon (;)
use the function mysqli_multi_query which supports multiple queries.
Unless you have a very good reason, modify your code so that it executes each query separately. MySQLi offers transaction support if you need that.*
The reason why you need a separate function is instructive; as mentioned in the docs:
An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
*: Actually, I'm not even sure the multi_query will execute both queries in the same transaction - I'm just guessing for your reason to use a multi-query.
Multiple statements should be terminated by semi colon
Try this
$sql = "DELETE FROM self_user_follower;
INSERT INTO self_user_follower
(username, profile_picture, full_name, user_id, last_updated)
VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id,
:query_last_updated)";

inserting multiple record using single mysql_query possible or not?

I'm working on a site in which I have to insert values in different table. so keeping this need in view, is it possible for me that can I use multiple query in single mysql_query in php or not.
for example:
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'); insert into tableB (xxx, xxx, xxx) values ('value1','value2','value3')")
I want to run multiple queries in single statement. Please suggest some solution.
No, it is not possible. The obsolete mysql_* API only allows for one query to be executed at a time. To do this you need to use the mysqli API and mysqli_multi_query().
A single MySQL "INSERT" statement can support multiple VALUE tuples if they're for the same table.
mysql_query("insert into tableA (e-mail, name) values ('xxx', 'xxx'), ('yyy','yyy')")
However, what you're trying to do is not possible with the mysql_* functions.
Although the mysqli_* API allows you to run multiple queries at once, I recommend you AGAINST doing that for at least 2 reasons:
It's always a good (actually, great) idea to use prepared statements, for security reasons. Prepared statements can be used with the MySQLi API as well as with PDO.
As you can see from the docs for mysqli_multi_query(), getting errors from that function can be cumbersome. The function, indeed, returns only "false" if the first query fails; to get results for other queries you need to call another function.
In general, why would you need to combine multiple queries together? Eventually, the time you'd save would be minimal.
Instead, if your goal is having more than one query executed together, and having the whole set of queries fail if one fails, you can use transactions (which also can speed up inserts in some cases). Both MySQLi and PDO support transactions: see examples here for PDO http://php.net/manual/en/pdo.transactions.php
PS: in general, it's a good idea to avoid using mysql_* functions entirely, as those APIs are deprecated.
Welcome to PDO:
With PDO am able to do something like:
$sql = "
insert into tableA (e_mail, name) values (:e_mail, :name);
insert into tableB (xxx1, xxx2, xxx3) values (:xxx1, :xxx2, :xxx3)
";
Just have the Query Prepared first then VOILA!!
OR Using the Transaction method:
$con->beginTransaction();
$sql1 = "insert into tableA (e_mail, name) values (:e_mail, :name)";
$sql2 = "insert into tableB (xxx, fff) values (:xxx, :fff)";
$sql3 = "insert into tableC (qqq, bbb) values (:qqq, :bbb)";
$con->commit();

How to insert data to several tables in MySQL?

I have only just begun learning about joining tables in MySQL. Now, I have a small project where I simply want to let the visitor insert data through a form. The data is then displayed in a HTML table with four rows, joining together two tables in my database. The "problem" is that the data should be submitted into those two different tables in my database.
I tried
$query = "INSERT INTO table1, table2 (col1, col2, col3, col4) VALUES ('value1', 'value2', 'value3', 'value4')";
but that doesn't seem to do it. What is the correct syntax for submitting form data to several database tables? Oh, and I read some similar threads mentioning using transactions. Is this necessary? My tables are run with MyISAM. Thanks!
You can read more about it from the MySQL Manual. In short, you cannot insert into multiple tables at once. This leaves you with three options:
Multiple INSERT statements
Triggers
Stored Procedures
The answer to this question: MySQL Insert into multiple tables? (Database normalization?) suggests using transactions, which will not work with MyISAM, but is a good FYI if you ever switch to InnoDB.
I really recommend you read up on Triggers. They can make your life a lot easier. But if you don't want to use them, look into PHP's mysqli_multi_query, which will allow you to execute two different queries at the same time, for example:
$query = "INSERT INTO table1 (col1,col2) VALUES ('$value1','$value2');";
$query = "INSERT INTO table2 (col3,col4) VALUES ('$value3','$value4');";
$result = mysqli_multi_query($dbcon, $query);
You can perform this by using MySQL Transactions By:
Try:
BEGIN
INSERT INTO table1 (col1, col2...ETC)
VALUES('value1', 'value2'...ETC)
INSERT INTO table2 (col1, col2...ETC)
VALUES('value1', 'value2'...ETC);
COMMIT;
With MyISM you will need to execute the query for each table you want to insert into, I do not believe that in a single query you can add to multiple tables.
In your case you can not use Transactions because they are not supported by your engine.
Your only solution is to use several separate queries, preferably within a transaction. Transactions are necessary if you want to make sure that the data from each query is inserted, in which case you COMMIT the transaction; should one of the queries fail, you can ROLLBACK.
P.S. Use InnoDB. It's better in pretty much any environment where INSERT queries make up at least 5% of all queries (sadly I cannot give the source as I had read it several months ago and no longer remember where).
I may be wrong, but you don't insert into multiple tables at the same time. You split it into two or more commands, each handling the specific insertion, whats the big deal, that one extra line of code (which makes everything clearer) too much of a hassle to type?
Look at it this way, if you write a large script, for instance a routine to process some data, the more you segment the code, the easier it is to debug, and, if necessary, inoculate instructions that are problematic, it will end up saving you time in the long run.
I have this problem before You can use multiple query function
$query = "INSERT INTO table1 (col1,col2) VALUES ('$value1','$value2')";
$query = "INSERT INTO table2 (col3,col4) VALUES ('$value3','$value4')";
$result = mysqli_multi_query($dbcon, $query);

How can I make hundreds of similar MySQL queries more efficient?

I have an array of information about links I've found on a webpage in a PHP script.
Each link needs to be inserted into a MySQL myisam table.
Right now, I loop through the array and run an insert query for each link.
Is there a more appropriate way to do this so that I'm using MySQL more efficiently?
You can insert several records with a single statement:
<?php
// Our MySQL query
$sql = "INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)";
mysql_query( $sql, $conn );
?>
Source: http://www.desilva.biz/mysql/insert.html
You can insert multiple values in a single statement using the following syntax:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
see Section 12.2.5 of the MySQL manual
This is especially advisable if the MySQL server is on a different host than the PHP server: in the example above, you need only a single network roundtrip rather than three.
If network latency is not an issue (if the MySQL server runs on the same server as PHP), use prepared statements like this:
$dbh = new PDO("mysql:host=127.0.0.1;port=3306;dbname=test", "root", "");
$sth = $dbh->prepare("INSERT INTO links(title, href) VALUES(:title, :href);");
while ($link = getNextLink()) {
$sth->execute( array( "title" => $link->title, "href" => $link->href ) );
}
Prepared statements are slightly faster when executed repeatedly, because the MySQL server has to parse the SQL and run the query planner/optimizer only once.
If the table has indices, you can disable them before inserting and enable them again after inserting, this makes inserting rows faster because the indices don't have to be updated after every insert (only possible for MyISAM, see section 12.1.7 of the Mysql manual):
ALTER TABLE links DISABLE KEYS
-- insert rows
ALTER TABLE links ENABLE KEYS
A while or a for each loop is sufficient enough I would think for this, seeing as the information is going to be large and I imagine dynamic.
You can use one query but if you have hundreds or thousands of pieces of information, or if you are going to be constantly updating the database with new data, then an array with a for each or while loop is best for this. If its just a one off with only a few pieces of information then just write out the QUERY yourself as follows
mysql_query("INSERT INTO table (column1, column2)
VALUES
('VALUE','VALUE'),('VALUE','VALUE')");

Categories