php - insert single set of data multiple times mysql -
i have insert single set of data multiple times , n rows.
insert mytable values ("john", 123, "us");
can insert n rows in single sql statement?
here n
dynamic value n user input , how make insert query n times , idea.
$sql = "insert `mytable` values(`field1`,`field2`,`field3`) values "; $count = 5; for($i=0;$i<$coutn;$i++) { $sql .= " ('john','123','us' )"; }
is correct way..
yep, can done easily, should this:
insert mytable values ("john", 123, "us"), ("carl", 123, "eu"), ("jim", 123, "fr");
however, programming practice specify columns of table in query, example:
insert mytable (column1, column2, column3) values ("john", 123, "us"), ("carl", 123, "eu"), ("jim", 123, "fr");
edit : can build query (in for
cycle), $total
user input:
$sql = "insert mytable (column1, column2, column3) values"; //build sql insert query ($i = 1; $i <= $total; $i++) { $sql .= " ($value1, $value2, $value3), "; } //trim last comma (,) $sql = rtrim($sql,","); //now, $sql var contains complex query. $result = mysql_query($sql);
as can see we not execute insert
statement in loop, rather build sql query text , then execute in 1 pass.
Comments
Post a Comment