View Full Version : Foreach Loop Help

07-31-2007, 04:57 AM

I'm trying to learn about arrays and how to access them. I have a form which allows a person to select multiple items. When I do a "foreach" and echo the results of the form, the results appear correctly.

When I try to insert the results into a table, I receive the following error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'York)' at line 1

Can someone help me with this INSERT query?

Here is the code for the form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<form action="checkbox-test.php" method="post">
<p>Select City:</p>
<p><input type="checkbox" name="place[]" value="New York">New York</p>
<p><input type="checkbox" name="place[]" value="Chicago">Chicago</p>
<p><input type="checkbox" name="place[]" value="London">London</p>
<p><input type="checkbox" name="place[]" value="San Francisco">San Francisco</p>
<p><input type="submit" value="submit"></p>


Here is the PHP script which processes the form:


require_once ('mysql_connect.php');

foreach($_POST['place'] as $pvalue){
$query = "INSERT INTO checkbox_test(place) VALUES ($pvalue)";
$result = mysql_query($query) or die(mysql_error());

//echo "$pvalue <br>";

My table name is checkbox_test and it contains two fields. The first field is ID which is primary and auto-incremented. The second field is place.

Thanks for the help.

07-31-2007, 05:16 AM
($pvalue) should probably (since its a string) be

$query = "INSERT INTO checkbox_test(place) VALUES ('$pvalue')";

07-31-2007, 10:30 AM

Thank you. That did the trick.