Multiple mysql INSERT statements in one query php [duplicate] - php

This question already has answers here:
Insert multiple rows with one query MySQL
(5 answers)
Closed 2 years ago.
Is this legal?
$string1= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
$string1 .= "INSERT INTO....;";
mysql_query($string1) or die(mysql_error());

For what it's worth, and depending on if you're inserting the same data into
the same tables, it's much better to insert multiple values with the one insert
e.g.
INSERT INTO a VALUES (1,23),(2,34),(4,33);
INSERT INTO a VALUES (8,26),(6,29);

No, mysql_query() only allows one query at a time.
You can insert multiple rows like this:
INSERT INTO table (col1, col2)
VALUES (1, 2), (3, 4), (5, 6)

From MySQL dev support MySQL dev forum
INSERT INTO table (artist, album, track, length)
VALUES
("$artist", "$album", "$track1", "$length1"),
("$artist", "$album", "$track2", "$length2"),
("$artist", "$album", "$track3", "$length3"),
("$artist", "$album", "$track4", "$length4"),
("$artist", "$album", "$track5", "$length5");
So insert goes as normal as always:
naming first the table name where we want to insert new row,
followed by naming column names in round brackets (Note: Not needed if you want to insert ALL columns),
followed by VALUES key name and then in round brackets comes the values that you want to insert for new ROW in the above table,
followed by COMMA and then another pair of round brackets with new values for new row in the mentioned table above
and this repeats N-times as long you have the data to insert.
Happy inserting multiple values with ONE insert statement. :)

Copy/paste example within a function and a loop (suppose $ids is an array)
public function duplicateItem($ids)
{
if (isset($ids[0])){ //at least one item
$sqlQuery = "INSERT INTO items (item_id, content) VALUES ";
for($i=0; $i<count($ids); $i++) {
if ($i == count($ids)-1){
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."');";
}else{
$sqlQuery .= "(".$ids[$i][0].", '".$ids[$i][1]."'),";
}
}
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());
}
}

In general, that's valid SQL since each statement ends with a semicolon, but PHP doesn't allow you to send more than one query at a time, in order to protect against SQL injection attacks that might exploit a poorly written script.
You can still use a syntax like:
INSERT INTO foo VALUES ('a1', 'b1'), ('a2', 'b2');

INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);

No. They are separate queries, and must be called as such.

// if $data is an array
$sqlQuery ="INSERT INTO tableName(col1, col2) VALUES ";
for($i=0; $i<count($data); $i++) {
$sqlQuery .="(".$data[$i][0].", '".$data[$i][1]."'),";
}
$sqlQuery = rtrim($sqlQuery, ','); // Remove last comma
mysql_query($sqlQuery) or die('Error, insert query failed: '.mysql_error());

Related

How to make PHP MYSQL Insert query only with values which are existed for certain columns?

I have 17 columns in my DB
I'm inserting values from different sources. Somewhere I haven't, for example, company/company_info values (I'm setting in PHP FALSE values for relevant variables).
So, I need some kind of PHP INSERT query to insert only not empty variables and columns of certain list.
For example, I could do:
$q = "INSERT INTO `$tname` (`phone`,`location`, `pagelang`, `company`, `company_url`, `phone_no_cc`, `phone_type`, `operator`, `pageviews`, `rating`, `comments_number`, `activity_by_days`, `activity_by_hours`) VALUES (
'$main_number', '$number_advanced_info[location]', '$pagelang', '$company[name]', '$company[site]', '$number_advanced_info[number_no_countrycode]', '$number_advanced_info[phone_type]', '$number_advanced_info[operator]', '$searches_comments[searches]', '$rating', '$searches_comments[comments]', '$history_search', '$daily_history'
);";
With insert of 14 columns and their values.
But sometimes I need to insert less columns/values and let MYSQL set default values for not listed columns. For Example, I want to insert only 5 columns.
$q = "INSERT INTO `$tname` (`phone`,`location`, `pageviews`, `rating`) VALUES (
'$main_number', '$number_advanced_info[location]', '$searches_comments[searches]', '$rating'
);";
Is there some CLASS or any solution like binding values which will automatically build query depending which values are not NULL?
I need some kind of code:
if (!$phone) {
$columns .= "`column_name`," ;
$values .= "value";
}

Inserting multiple rows in MySQL using PHP [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is the database query faster if I insert multiple rows at once:
like
INSERT....
UNION
INSERT....
UNION
(I need to insert like 2-3000 rows)
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Source
If you have your data in a text-file, you can use LOAD DATA INFILE.
When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.
Optimizing INSERT Statements
You can find more tips on how to speed up your insert statements on the link above.
Just use a SELECT statement to get the values for many lines of the chosen columns and put these values into columns of another table in one go. As an example, columns "size" and "price" of the two tables "test_b" and "test_c" get filled with the columns "size" and "price" of table "test_a".
BEGIN;
INSERT INTO test_b (size, price)
SELECT size, price
FROM test_a;
INSERT INTO test_c (size, price)
SELECT size, price
FROM test_a;
COMMIT;
The code is embedded in BEGIN and COMMIT to run it only when both statements have worked, else the whole run up to that point gets withdrawn.
Here is a PHP solution ready for use with a n:m (many-to-many relationship) table :
// get data
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
// prepare first part of the query (before values)
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
//loop the table 1 to get all foreign keys and put it in array
foreach($table_1 as $row) {
$query_values[] = "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW())";
}
// Implode the query values array with a coma and execute the query.
$db->query($query . implode(',',$query_values));
EDIT : After #john's comment I decided to enhance this answer with a more efficient solution :
divides the query to multiple smaller queries
use rtrim() to delete last coma instead of implod()
// limit of query size (lines inserted per query)
$query_values = "";
$limit = 100;
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
foreach($table_1 as $row) {
$query_values .= "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW()),";
// entire table parsed or lines limit reached :
// -> execute and purge query_values
if($i === array_key_last($table_1)
|| fmod(++$i / $limit) == 0) {
$db->query($query . rtrim($query_values, ','));
$query_values = "";
}
}
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";

How to insert multiple data in table [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is the database query faster if I insert multiple rows at once:
like
INSERT....
UNION
INSERT....
UNION
(I need to insert like 2-3000 rows)
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Source
If you have your data in a text-file, you can use LOAD DATA INFILE.
When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.
Optimizing INSERT Statements
You can find more tips on how to speed up your insert statements on the link above.
Just use a SELECT statement to get the values for many lines of the chosen columns and put these values into columns of another table in one go. As an example, columns "size" and "price" of the two tables "test_b" and "test_c" get filled with the columns "size" and "price" of table "test_a".
BEGIN;
INSERT INTO test_b (size, price)
SELECT size, price
FROM test_a;
INSERT INTO test_c (size, price)
SELECT size, price
FROM test_a;
COMMIT;
The code is embedded in BEGIN and COMMIT to run it only when both statements have worked, else the whole run up to that point gets withdrawn.
Here is a PHP solution ready for use with a n:m (many-to-many relationship) table :
// get data
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
// prepare first part of the query (before values)
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
//loop the table 1 to get all foreign keys and put it in array
foreach($table_1 as $row) {
$query_values[] = "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW())";
}
// Implode the query values array with a coma and execute the query.
$db->query($query . implode(',',$query_values));
EDIT : After #john's comment I decided to enhance this answer with a more efficient solution :
divides the query to multiple smaller queries
use rtrim() to delete last coma instead of implod()
// limit of query size (lines inserted per query)
$query_values = "";
$limit = 100;
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
foreach($table_1 as $row) {
$query_values .= "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW()),";
// entire table parsed or lines limit reached :
// -> execute and purge query_values
if($i === array_key_last($table_1)
|| fmod(++$i / $limit) == 0) {
$db->query($query . rtrim($query_values, ','));
$query_values = "";
}
}
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";

insert multiple row in sql database with php

I want to insert multiple row in sql with php, after checking few conditions.
The condition is, if 'cat' and 'preview' is not null then row one will be submitted and if 'cat','preview','cat2','preview2' is not null then two row will submitted with first row's value 'cat' and'preview and 2nd row's value 'cat2' and 'preview2'.
i tried these code, but i see - Undefined variable: sql
whats wrong with my condition?
else if(isset($cat)and ($cat!=="") and isset($preview)and ($preview=="") and
(isset($cat2))and ($cat2!=="") and (isset($preview2))and ($preview2!==""))
{
$sql = "INSERT INTO files (cat, preview, file, art) VALUES
('".$cat."','".$preview."','".$file."','".$art."')
('".$cat2."','".$preview2."','".$file2."','".$art2."')";
}
your code just had query mistake that you wanted to insert two row in just one insert command.use this code that seperates the insert commands :
else if(!empty($cat) and !empty($preview) and
!empty($cat2) and !empty($preview2))
{
$sql = "INSERT INTO files (cat, preview, file, art) VALUES
('".$cat."','".$preview."','".$file."','".$art."');";
$sql .= " INSERT INTO files (cat, preview, file, art) VALUES ('".$cat2."','".$preview2."','".$file2."','".$art2."');";
}
I personally think that the logic you have with your conditions may need rethinking. For instance, if you save your values into arrays, you can automate this process:
// Save first values
$sqlArgs[] = array($cat,$preview,$file,$art);
// Save second values
$sqlArgs[] = array($cat2,$preview2,$file2,$art2);
// Loop through each row.
foreach($sqlArgs as $key => $array) {
// If the `cat` or the `preview` empty, skip
if(!empty(trim($array[0])) && !empty(trim($array[1])))
$sql[] = "'".implode("','",$array)."'";
}
// If the sql has rows continue
if(!empty($sql)) {
// Build the statement rows with implode() of values.
// This assumes these are not user-input values or that you have
// thoroughly sanitized the values.
$statement = "INSERT INTO `files` (`cat`,`preview`,`file`,`art`) VALUES (".implode("),(",$sql).")";
// Preview statement
print_r($statement);
}
This approach will take care of 0,1, or 2 inserts (or more if necessary) based on the two keys cat & preview being filled.
Insert query with ; is not one query...
For example
Insert into mytable (a,b,c) values (1,2,3);
Insert into mytable (a,b,c) values (4,5,6);
Insert into mytable (a,b,c) values (7,8,9);
is not one query, this is 3 insert queries.
That is mean when insert values (4,5,6) have error, values (1,2,3) query is successed....
We want if one row failed, all insert query fail.
Therefore, we don't write insert query with ;
Example query:
Insert into mytable values(1, 2, 3), (4, 5, 6), (7, 8, 9);

Using On Duplicate Key Update with an array

I'm relatively new to MYSQL and am having trouble combining idea I have read about. I have a form generated from a query. I want to be able to insert or update depending on whether there is currently a matching row. I have the following code which works for inserting but I;m struggling with the On DUPLICATE UPDATE part I keep getting a message saying there is an error in my syntax or unexpeted ON depending on how I put the ' .
require_once("connect_db.php");
$row_data = array();
foreach($_POST['attendancerecordid'] as $row=>$attendancerecordid) {
$attendancerecordid=mysqli_real_escape_string($dbc,$attendancerecordid);
$employeeid=mysqli_real_escape_string($dbc,($_POST['employeeid'][$row]));
$linemanagerid=mysqli_real_escape_string($dbc,($_POST['linemanagerid'][$row]));
$abscencecode=mysqli_real_escape_string($dbc,($_POST['abscencecode'][$row]));
$date=mysqli_real_escape_string($dbc,($_POST['date'][$row]));
$row_data[] = "('$attendancerecordid', '$employeeid', '$linemanagerid', '$abscencecode', '$date')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES '.implode(',', $row_data)
ON DUPLICATE KEY UPDATE abscencecode = $row_data[abscencecode];
echo $sql;
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
}
The various echo statements are showing that the correct data is coming through and my select statement was as expected before I added in the ON DUPLICATE statement.
You need to fix the way the sql statement is constructed via string concatenation. When you create an sql statement, echo it and run it in your favourite mysql manager app for testing.
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES ('.implode(',', $row_data).') ON DUPLICATE KEY UPDATE abscencecode = 1'; //1 is a fixed value yiu choose
UPDATE: Just noticed that your $row_data array does not have named keys, it just contains the entire new rows values as string. Since you do bulk insert (multiple rows inserted in 1 statement), you have to provide a single absencecode in the on duplicate key clause, or you have to execute each row in a separate insert to get the absence code for each row in a loop.

Categories