...

View Full Version : Foreach Loop Help



focus310
07-31-2007, 03:57 AM
Hi,

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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>
<body>
<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>

</form>
</body>
</html>

====
Here is the PHP script which processes the form:


<?php


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.

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



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

focus310
07-31-2007, 09:30 AM
Hello:

Thank you. That did the trick.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum