数组未插入数据库

时间:2013-09-22 17:45:21

标签: php select

<form action="4.php" method="POST">
<select name="select2[]" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<select name="select[]" multiple>
  <option value="volvo1">Volvo1</option>
  <option value="saab2">Saab2</option>
  <option value="opel3">Opel3</option>
  <option value="audi4">Audi4</option>
</select>
<input type="submit" name="sub" value="submit">
</form>

4.php

<?php
mysql_connect("localhost", "root", "");
$db=mysql_select_db("test");
if(isset($_POST['sub'])) {

$r=$_POST['select2'];
$f=$_POST['select'];


    $val1  = implode("", $r);


    $val2  = implode("", $f);


    $r=mysql_query("insert into test1 (test,test1) values ('$val1','$val2') ");
}


?>

我使用的是php语言。我正在使用select multiple并尝试在我的数据库中添加值,但仅在一行中添加所有值

2 个答案:

答案 0 :(得分:1)

尝试使用implode(",", $r)代替implode("", $r)

<?php
mysql_connect("localhost", "root", "");
$db=mysql_select_db("test");
if(isset($_POST['sub'])) {

$r=$_POST['select2'];
$f=$_POST['select'];

    $val1  = implode(",", $r);// to save it as string

    $val2  = implode(",", $f);

    $r=mysql_query("insert into test1 (test,test1) values ('$val1','$val2') ");
}

// and to retrieve data 
explode(",", $result); // to convert it from string to array

&GT;

答案 1 :(得分:0)

你必须将它逗号分隔为@jetawe说,但我认为他的查询不会起作用。我建议你在两个查询中做到这一点,以保持简单:

   $val1  = implode("', '", $r);  // add quotes
   $val2  = implode("', '", $f);

   $result_1 = mysql_query("insert into test1 (test) values ($val1) ");
   $result_2 = mysql_query("insert into test1 (test1) values ($val2) ");

但我必须提到,应该更好地命名变量以避免混淆。努力命名变量以减少代码中的错误 此外,您还必须使用另一种方式来连接和查询数据库。 The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead