I have a form with a number of checkboxes, which are generated from unique values in a MySQL table:
<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. 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:
$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:
echo "<input type=\"checkbox\" name=\"from_user[]\" value=\"".$from_user."\" checked=\"checked\">".$from_user."<br>";
}
IN
expects comma separated values:
$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
$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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.