tags:

views:

77

answers:

4

Hello,

This is my html partial code

<select name="number[]" style="width: 350px;" multiple="multiple" size="2">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>

PHP code

$name = $_POST["name"];
$number= $_POST["number"];
$sql = mysql_query("SELECT * FROM users WHERE name LIKE '%$name%' AND ");

What should i add after AND for the number so that query will work? I tried foreach but it didnt exactly work in query.

A: 
$number= $_POST["number"][i];

put this in your loop

Treby
A: 

How about:

$name = $_POST["name"];
$number= $_POST["number"];

if(!is_array($number)){
  // some error message or what.
}

$squery = '';
$a = array();
foreach($number as $n){
  // do some validation for $n
  // $number should be an array, so don't validate it.
  $a[] = "`number` = '$n'";
}
$squery = implode(' OR ',$a);
unset($a);

$query = "SELECT * FROM users WHERE `name` LIKE '%$name%' AND (".$squery.")";
$res = mysql_query($query);
thephpdeveloper
Slick, thank you
@UFOman: can you upvote at least the good valided by the user answer won't have a -1, tks to @phildah
RageZ
Still doesn't contain any output escaping, so my -1 stays.
phidah
if you insist.~
thephpdeveloper
+1  A: 

something like this I suppose

$sql = mysql_query("SELECT * FROM users WHERE name LIKE '%$name%' AND number IN (" . implode(',', $_POST['number']) . ')');

the implode documentation

also please not you should be careful about escaping the data coming from users or your website is going to be SQL injection vulnerable.

RageZ
@phidah: are you trying to be kind of ayatollah or ?
RageZ
A: 

My approach would be something like this:

<?php
if(is_array($_POST['number']))
{
   $numbers = implode("','", array_walk($_POST['number'],' mysql_real_escape_string')));
   $result = mysql_query("SELECT * FROM users WHERE name LIKE '%" . mysql_real_escape_string($name%) . "' AND number IN ('" . $numbers . "')") or die(mysql_error());
}
?>
phidah
@phidah: for the record your first answer used `addslashes` which is not a proper escapement
RageZ
@phidah: + if you take a closer look that bit of code won't work `array_walk($_POST['number'],'mysql_real_escape_string'))` `array_walk ` return a boolean......
RageZ
-1 for messy code.
thephpdeveloper
RageZ if you could drop the hetz Stackoverflow would be a better place. At least I used _any_ escaping initially :)
phidah
@thephpdeveloper: I agree. Tried to clean it up a bit.
phidah