PHP - 无法向MySQL添加多个下拉菜单选项

时间:2013-09-02 15:03:32

标签: php implode mysql-real-escape-string

我在向MySQL数据库添加多个下拉菜单选项时遇到了困难。我从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')");
}

?>

当我运行此代码时,我不断收到与mysql_real_escape_string()implode()函数相关的错误消息。

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"

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

不幸的是,我没有使用这些功能的经验。有谁可以请指出我在这里出了什么问题?我正在使用WAMP (PHP 5.3.8)Google Chrome (Version 24.0.1312.52)

1 个答案:

答案 0 :(得分:0)

正如Bart所说,mysql_real_escape_string适用于字符串,而不适用于数组。 您$_POST['game']是数组的原因是因为您将其命名为game[]。如果将名称更改为game,则可以尝试使用一个值。

虽然我们希望代码可以使用多种选择。您可以像这样更改PHP代码:

<?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')");
}
?>

顺便问一下,你能告诉我们你的数据库结构是什么吗?保存用户在一个单元格中选择的所有值,这似乎是一个很大的错误。它应该可行,但它不是一种在数据库中存储数据的好方法(它不符合任何数据库标准)。

修改

此外,我注意到有一种更简单的方法可以解决它(似乎有人编写代码错误地放了两行):

<?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')");
}
?>