Jump to content

Exploded Data - Insert into DB


3raser

Recommended Posts

Is there a way to send exploded data into a database without using multiple loops just to do so? My current code, but it only inserts the name value in the database as Array.

 

	$chicken_names = mysql_real_escape_string($_POST['names']);
	$chicken_names_exp = explode(' ', $_POST['names']);

	foreach($chicken_names_exp as $value)
	{
		mysql_query("INSERT INTO names VALUES (null, '$chicken_names_exp"', '". $_POST['type'] ."')");
	}

	echo "Success! You have successfully sent in your chicken names! <a href='index.php'>Home</a>";

Link to comment
https://forums.phpfreaks.com/topic/233281-exploded-data-insert-into-db/
Share on other sites

You can avoid running the query in the loop as below. I've added some comments in the code to explain.

 

$_POST['names'] = preg_replace('~[\s]{2,}~', ' ', $_POST['names']); // Replace multiple spaces with one space to avoid empty records
$chicken_names = mysql_real_escape_string($_POST['names']);
$chicken_names_exp = explode(' ', $chicken_names);
$query = "INSERT INTO names VALUES "; // Start building query string
$records = array(); //initialize an empty array to hold the records

foreach($chicken_names_exp as $value) {
$records[] = "(null, '$value', '{$_POST['type']}')"; // build an array of values to insert
}

$query .= implode( ', ', $records ); // implode the array of values with a comma, and concatenate to query string

if( $result = mysql_query($query) ) {
echo "Success! You have successfully sent in " . mysql_affected_rows() . " chicken names! <a href='index.php'>Home</a>";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.