将值数组从表单传递给sql查询WHERE IN子句

时间:2012-08-11 11:20:33

标签: php mysql arrays forms

我有一个包含许多复选框的表单,这些复选框是从MySQL表中的唯一值生成的:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
    $query5="SELECT distinct from_user from tracks WHERE uploaded_page='$this_path_short' ORDER BY from_user";
    $result5=mysql_query($query5) or die(mysql_error());
    while ($row = mysql_fetch_array($result5)) {
        $from_user = $row['from_user'];
        echo "<input type=\"checkbox\" name=\"from_user[]\" value=\"AND ".$from_user."\" checked=\"checked\">".$from_user."<br>";
    }
?>
<input type="submit" name="submit" value="filter"><br>

然后我想将'from_user'值的数组传递给页面上的另一个MySQL查询。我可以得到这样的值:

$names=implode(" ", $_POST['from_user']);

但我不知道如何在以下MySQL查询中包含此数组:

$query1="SELECT * FROM tracks WHERE from_user IN **array goes here**)";

2 个答案:

答案 0 :(得分:0)

$query1='SELECT * FROM tracks WHERE from_user IN ('.implode(',',$_POST['from_user']).')';

答案 1 :(得分:0)

删除AND,以便复选框值如下所示:

echo "<input type=\"checkbox\" name=\"from_user[]\" value=\"".$from_user."\" checked=\"checked\">".$from_user."<br>";
    }

IN需要以逗号分隔的值:

$names=implode(",", $_POST['from_user']);    
$query1="SELECT * FROM tracks WHERE from_user IN (".$names."))";

<强> !!!!但是:请请使用预备语句,因为您的代码对SQL注入是开放的: http://php.net/manual/de/mysqli.prepare.php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
}

$result = null;
$names = implode(",", $_POST['from_user']);  

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM tracks WHERE from_user IN (?)")) {

  /* bind parameters for markers */
  $stmt->bind_param("s", $names);

  /* execute query */
  $stmt->execute();

  /* bind result variables */
  $stmt->bind_result($result);

  /* fetch value */
  $stmt->fetch();

  print_r($result);

  /* close statement */
  $stmt->close();
}

/* close connection */
$mysqli->close();