I have 5 text box contaning 5 contact no of a particular person. I want to insert those 5 contact no in tblContact(person_id|contact_no). Can I insert these 5 contact no in one sql statement OR I have to call a loop to insert 5 records?
INSERT INTO `tblContact` (`person_id`, `contact_no`) VALUES
('PERSON_ID_VALUE_1', 'CONTACT_NO_VALUE_1'),
('PERSON_ID_VALUE_2', 'CONTACT_NO_VALUE_2'),
('PERSON_ID_VALUE_3', 'CONTACT_NO_VALUE_3'),
('PERSON_ID_VALUE_4', 'CONTACT_NO_VALUE_4'),
('PERSON_ID_VALUE_5', 'CONTACT_NO_VALUE_5');
Many databases have a multi-row insert capability and MySQL is one of them. You can use (in 5.0+, not sure about earlier versions although a brief look at the 3.23/4.0/4.1 docs seems to indicate yes) something like:
insert into tblContact (person_id,contact_no) values
(1, '555-5555'),
(2, '555-1234');
More details here.
Aside: In genneral, if your database didn't support multi-row insert, you'd probably just use a transaction around the group of individual insert statements. We've found that multi-row inserts actually give us a pretty hefty speed increase (on our DBMS anyway - YMMV).
you can insert your 5 records in 1 insert statements.
like: insert into tblContact(person_id, contact_no) values(1,'145566'),(2,'233366'),(3,'564666')
Related
In the old question asked below the top answer describes how to speed up the MySQL insert process. Since this an old question I'm curious on how to do this with prepared statements. I use MySQL with innoDB. I'll paste in an example from the answer here for people who don't want to check the link.
Here I'll describe 3 methods for inserting data, ranging from slow to
fast:
The following is extremely slow if you have many rows to insert:
INSERT INTO mytable (id,name) VALUES (1,'Wouter');
INSERT INTO mytable (id,name) VALUES (2,'Wouter');
INSERT INTO mytable (id,name) VALUES (3,'Wouter');
This is already a lot faster:
INSERT INTO mytable (id, name) VALUES
(1, 'Wouter'),
(2, 'Wouter'),
(3, 'Wouter');
And this is usually the fastest:
Have CSV file that looks like this:
1,Wouter
2,Wouter
3,Wouter
And then run something like
LOAD DATA FROM INFILE 'c:/temp.csv' INTO TABLE mytable
old question
This is obvious an old answer. I want to know how to do this with prepared statements in a way that will insert as fast as possible, but let's go one step at a time. First I want to know how to do this with a prepared statements. Any examples that can be given will be much appreciated. I will reply or edit this question with any extra information that you may need.
I'm using mysqli_ *Edited for Rick James's question.
I'm going to do my best and make an educated guess on how this can be done. Please correct me if I'm wrong.
I think I can convert
INSERT INTO mytable (id, name) VALUES
(1, 'Wouter'),
(2, 'Wouter'),
(3, 'Wouter');
into
$bindParamsToBuild = '($myArray[key], ?,?),'
for (i = 0; i < count($myArray); i++)
{
if (i === count($myArray))
{
$bindParamsToBuild += '($myArray[key], ?,?);';
}
else
{
$bindParamsToBuild += '($myArray[key], ?,?),';
}
}
"INSERT INTO mytable (id, name) VALUES".$bindParamsToBuild;
Are you using PDO or mysqli?
If using mysqli, use real_escape_string() separately on each item in the list. It is a bit tedious but can be made easier by gradually building the insert string. I suggest not putting more than 100 items into a single INSERT.
https://stackoverflow.com/a/780046/1766831 is a pretty good discussion of the details. (But be sure to use mysqli_*, not mysql_*.)
Plan A: Construct the query as discussed in some of those links. Use real_escape_string and PHP string operations instead of "prepare".
Plan B: Build a string with lots of question mark. Simultaneously, build an array with the values to put into those question marks. Then do a single "prepare" to finish the multi-row INSERT statement.
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);
this the condition: there is a form in html and php haivng around 120 fields its for a website i am making this form on submitting goes to a php page where i first retrive all the values using $_REQUEST[]and then using insert query insert all of them in their specific coloums in the same table in my mysql database. Now i will have to do all the process again for updating these values. Becuase syntax for insert query and update query are quite different .
I dont want to write another 100 lines of code . Is there any way to use the code i wrote inside my insert query to use to update the data.?
Actually in MySQL there is an alternative syntax for insert that is very similar to the syntax for update. You can write
insert customer set customerid=12345, firstname='Fred', lastname='Jones
etc.
Personally I prefer this syntax because it's easy to see what value is going into each field. This is especially true on records with long lists of fields.
On the minus side, it's not standard SQL, so if you ever decide to port your app to a different database engine, all your inserts would have to be rewritten.
Another option I've occasionally used is to write a little function to create your insert and update statements. Then the syntax of your function can be the same, no matter how different the generated code is.
Another alternative, and depending on requirements and keys, you could use:
replace into tbl (<cols>) values (<vals>)
which will insert if not exist, or replace based on keys (insert/update in one query)
or if you are only inserting and don't want to insert twice, you could use:
insert ignore into tbl (<cols>) values (<vals>)
where if the record is already inserted based on keys, it is gracefully ignored
for more info http://dev.mysql.com/doc/refman/5.0/en/replace.html
There is a quite similar syntax for INSERT and UPDATE:
INSERT INTO <table> SET
column1 = value1,
column2 = value2,
...
;
UPDATE <table> SET
column1 = value1,
column2 = value2,
...
WHERE <condition>
;
INSERT INTO yourtable (field1, field2, field3, ...)
VALUES ($field1, $field2, $field3, ...)
ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), etc...
Details on this construct here.
Is it possible to insert a row into multiple tables at once? If you do several tables related by an ID; what is the best way to ensure integrity is maintained in case an INSERT fails?
That's exactly what transactions are for. If any of the commands fail, the whole thing since START TRANSACTION is rolled back:
START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'foo','bar');
INSERT INTO someothertable VALUES (LAST_INSERT_ID(),'baz');
COMMIT;
This being MySQL, you can't use transactions with MyISAM tables (you'll need the tables to use some engine that supports this, probably InnoDB).
This will never be inserted into the table (normally you'd have some branching, e.g. an IF):
START TRANSACTION;
INSERT INTO sometable VALUES(NULL,'data','somemoredata');
ROLLBACK;
Caveat: SQL commands which change the database structure (e.g. CREATE,ALTER,DROP) cannot be rolled back!
Use transactions, luke.
MySQL can insert multiple rows (search for 'multiple rows') like this:
INSERT INTO table (field1, field2, ...) VALUES (value1, value2), (value3, value4), etc...
However, there's no way to tell what got inserted and what wasn't due to constraint violations, beyond the query returning a count of records, duplicates, and warnings. You also can't use last_insert_id() to figure out the IDs of the new rows, as that only returns the LAST id that was created, not a set of ids.
If you need to guarantee integrity, then use single row insert statements and transactions.
I have these tables: My final mysql db, could someone check if the tables are correctly made?
How can I make an Insertion of an ad here?
Is join used on insert also?
Thanks
Clarification: I need to insert values into multiple tables here, and don't know how to do it else than using multiple INSERT INTO statements.
So I wonder if there is anyway to make just ONE statement (one line) and use JOIN to INSERT?
As far as I'm aware of, you can't INSERT data into multiple tables Within one plain SQL statement.
There are many database abstraction frameworks out there which can do something like that (DOCTRINE TO THE RESCUE!!) but thats a whole other story.
SQL for it self it not capable of such things.
No it's not possible with an INSERT statement to insert into multiple tables. But you could use a stored procedure that would nicely batch the various inserts, and the application would have only one SQL command to emit.
I don't understand your first question about the ads. As for the second, JOIN will not be used on a standard table unless you are using it in an INSERT...SELECT statement, which you very likely aren't.