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
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>";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.