-4

I was wondering if its possible to use multiple insert query in a single php code. Like when I clicked the save button. My php code will perform multiple insertion on a same table? Is it possible?

Example: tb_people with field 'id','name'

I have 3 name inputs that I need to put a value if a click the save button it will save?

Example code:

<?php
  if(isset($_POST['save']))
  {
    $name1 = $_POST['name1'];
    $name2 = $_POST['name2'];
    $name3 = $_POST['name3'];
    mysql_query("INSERT into tb_people(name) VALUES ('$name1')");
    mysql_query("INSERT into tb_people(name) VALUES ('$name2')");
    mysql_query("INSERT into tb_people(name) VALUES ('$name2')");
  }
?>

Is this possible? I'm curios cause im planning to use this kind of idea.

ztirom
  • 4,292
  • 3
  • 27
  • 39

3 Answers3

2

Yes. But learn more about MySQL before using it.

$name1 = mysql_real_escape_string($_POST['name1']);
$name2 = mysql_real_escape_string($_POST['name2']);
$name3 = mysql_real_escape_string($_POST['name3']);
mysql_query("INSERT INTO `tb_people` (`name`) VALUES ('$name1'), ('$name2'), ('$name3');");

xkcd
> xkcd


You can even do this:

HTML:

<input type="text" name="name[]" />
Repeat the above as many times as you like - you can even add more with JavaScript!

PHP:

$toinsert = array_map(function($n) {
    return "('".mysql_real_escape_string($n)."')";
},$_POST['name']);
mysql_query("INSERT INTO `tb_people` (`name`) VALUES ".implode(", ",$toinsert));

MySQL is very powerful. Try doing that with a prepared query!

PS. If, like me, you think mysql_real_escape_string is a fuckton to type each time...

function dbesc($n) {return mysql_real_escape_string($n);}
Community
  • 1
  • 1
Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
0

Yes, this is possible.

All this is doing is calling 3 mysql queries to the database.

Your code example should work perfectly fine for that as well.

vxstorm
  • 173
  • 1
  • 15
-1

Your code should work. It is better to have some protection against SQL injection as below.

  • I have changed addslashes to mysql_real_escape_string. So now it should be alright.

    $name1 = mysql_real_escape_string($_POST['name1']); $name2 = mysql_real_escape_string($_POST['name2']); $name3 = mysql_real_escape_string($_POST['name3']); mysql_query("INSERT INTO tb_people (name) VALUES ('$name1'), ('$name2'), ('$name3');");

Dulitha K
  • 2,038
  • 1
  • 19
  • 18