简体   繁体   English

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

[英]Passing array of values from form to sql query WHERE IN clause

I have a form with a number of checkboxes, which are generated from unique values in a MySQL table: 我有一个带有许多复选框的表单,这些复选框是从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>

I would then like to pass the array of 'from_user' values to another MySQL query on the page. 然后,我想将“ from_user”值的数组传递给页面上的另一个MySQL查询。 I can get the values like this: 我可以得到像这样的值:

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

But I am not sure how to include this array in the following MySQL query: 但是我不确定如何在以下MySQL查询中包含此数组:

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

Remove the AND so the checkbox value looks like this: 删除AND因此复选框值如下所示:

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

IN expects comma separated values: IN期望用逗号分隔的值:

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

!!!! !!!! BUT: Please, please, please use prepared statements because your code is wide open to SQL Injection: http://php.net/manual/de/mysqli.prepare.php 但是:请,请使用准备好的语句,因为您的代码可以进行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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM