Question

I'm having difficulty adding multiple drop down menu options to a MySQL database. I obtained the following code from freezecoders.com

<html>
<body>
<form method="post" action="index.php">
Select your favourite game:<br/>
<select name="game[]" multiple="multiple">
<option>Football</option>
<option>Volleyball</option>
<option>Badminton</option>
<option>Cricket</option>
</select>
<input type="submit" name="submit">
</form>
</body>
</html>

<?php
if(isset($_POST['submit']))
{
$query=mysql_connect('localhost','root','');
mysql_select_db("freeze",$query);
$choice=mysql_real_escape_string($_POST['game']);
$choice1=implode(',',$choice);
mysql_query("insert into tb values('','$choice1')");
}

?>

When I run this code I keep getting error messages relating to mysql_real_escape_string() and implode() functions.

The error message are "Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in C:\WAMP\www\COSHH\test\index.php on line 8"

And

"Warning: implode() [function.implode]: Invalid arguments passed in C:\WAMP\www\COSHH\test\index.php on line 9" 

Unfortunately for me I'm not experienced in using these functions. Can someone please point out what's going wrong for me here? I'm using WAMP (PHP 5.3.8) and Google Chrome (Version 24.0.1312.52)

Was it helpful?

Solution

As Bart said mysql_real_escape_string works with strings, not with arrays. The reason your $_POST['game'] is an array is because you have it named game[]. You can try with one value if you change the name to game.

Although we want the code to work with multiple choices. You can change the PHP code like this:

<?php
if(isset($_POST['submit']))
{
    $query=mysql_connect('localhost','root','');
    mysql_select_db("freeze",$query);
    $choice = array();
    foreach($_POST['game'] as $game) {
        $choice[]=mysql_real_escape_string($game);
    }
    $choice1=implode(',',$choice);
    mysql_query("insert into tb values('','$choice1')");
}
?>

By the way, can you tell us what is your database structure? It seems you are making a big mistake with saving all the values the user picked in just one cell. It should work, but it's not a very good way of storing data in database (it's not compilant with any data bases standards).

EDIT:

Also I noticed there is an easier way to fix it (it seems someone who wrote the code misplaced two lines):

<?php
if(isset($_POST['submit']))
{
    $query=mysql_connect('localhost','root','');
    mysql_select_db("freeze",$query);
    $choice=implode(',',$_POST['game']);
    $choice1=mysql_real_escape_string($choice);
    mysql_query("insert into tb values('','$choice1')");
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top