我很难将多个下拉菜单选项添加到MySQL数据库中。我从冷冻编码网站获得了以下代码
<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)
正如Bart所说,mysql_real_sescape_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')");
}
?>