2 Replies - 7982 Views - Last Post: 07 December 2009 - 02:49 AM Rate Topic: -----

#1 codewalkz  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 6
  • Joined: 01-December 09

PHP Mysql Insert Multiple ROWS

Post icon  Posted 07 December 2009 - 02:37 AM

I currently have the below code used to insert multiple rows using only 1 form and 1 query. New records are inserted into the database since I have the the value "id" as auto-increment. The problem is, the values I supplied are not inserted into the database.
<?php
mysql_connect("localhost", "dbusername", "xxxxxxx") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

if(isset($_POST['save']))
{
$name=$_POST['name'];
$key1=$_POST['key1'];

foreach($_POST['user'] as $post_key){ 
		$query_string = " ('".$post_key[name]."', '".$post_key[key1]."'),"; 
	} 
	$query_string = substr_replace($query_string,"",-1); 

	$mysql_return = mysql_query("INSERT INTO `counts` (`name`, `key1`) VALUES".$query_string) or die(mysql_error()); 

	($mysql_return == 1);
	

}
?>
<form method="post">
<input type="text" name="user[0]['key1']" value="active">Key1
<input name="user[0]['name']" type="text" />Name1<br />
<input type="text" name="user[1]['key1']" value="active">Key2
<input name="user[1]['name']" type="text" />Name2<br />
<input name="save" type="submit" value="submit" /><br />
</form>


I say thanks fella! ^_^

This post has been edited by codewalkz: 07 December 2009 - 02:39 AM


Is This A Good Question/Topic? 0
  • +

Replies To: PHP Mysql Insert Multiple ROWS

#2 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1004
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: PHP Mysql Insert Multiple ROWS

Posted 07 December 2009 - 02:42 AM

foreach($_POST['user'] as $post_key){ 
		$query_string = " ('".$post_key[name]."', '".$post_key[key1]."'),"; 
	}


You will be overwriting $query_string each time with that code.

You should do this (concatenation):
$query_string = "";
foreach($_POST['user'] as $post_key){ 
	$query_string .= " ('".$post_key[name]."', '".$post_key[key1]."'),"; 
}


I'm not sure if that's your specific issue, but it should help either way.
Was This Post Helpful? 0
  • +
  • -

#3 codewalkz  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 6
  • Joined: 01-December 09

Re: PHP Mysql Insert Multiple ROWS

Posted 07 December 2009 - 02:49 AM

Forgive my ignorance but what will be the value of the query_string if it's at the upper part of the foreach?

$query_string = "";
foreach($_POST['user'] as $post_key){ 
	$query_string .= " ('".$post_key[name]."', '".$post_key[key1]."'),"; 
}
	$query_string = substr_replace($query_string,"",-1); 

	$mysql_return = mysql_query("INSERT INTO `counts` (`name`, `key1`) VALUES".$query_string) or die(mysql_error()); 

	($mysql_return == 1);



Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1