Jump to content

[SOLVED] Multiple checkboxes selects not displaying all results


kb4life

Recommended Posts

Can someone help me with my code. I'm completely new at php. I have a form that populates checkboxes from a mysql database. When a user selects multiple items I want it to display the results.

Here's the form.

$query=("select first,id from contacts");
$result=mysql_query($query);

$num=mysql_numrows($result);


?>
<form action="output12.php" method="post">
<?

echo "<b><center>Database Output</center></b><br><br>";
$i = 0;
if ($num < 1) {
print "There are No Records";
}
else
{
//This bit does the loop
while($row=mysql_fetch_array($result)){
//while ($num > $i) {
$ID = @$row["first"];
$NA = @$row["id"];

print "<input type=\"checkbox\" name=\"first\" value=\"$ID\">$ID";
echo "<br>";
$i++;
}
}
?>
<tr><td align="right"><input type="submit" Value="Display"></td></tr>
</table>
</form>

 

Here's the output code

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$first = $_POST['first'];
$sql = mysql_query("select * from contacts where first like '%$first%'");

while ($row = mysql_fetch_array($sql)){
echo 'ID: '.$row['id'];
echo '<br/> First Name: '.$row['first'];
echo '<br/> Last Name: '.$row['last'];
echo '<br/> Phone: '.$row['phone'];
echo '<br/><br/>';
}	
?>

 

If the user selects two items it only displays one result. I want to be able to display all results selected.

 

First, you need to pass an array to the POST.  So change the name to:

 

name=\"first[]\"

 

Second, you would have to add these conditions to your query, dynamically.  Either loop through and build 1 query, or loop through and execute multiple queries.

Thanks Maq for helping me out. So this is what I did.

 

$first = $_POST['first'];

foreach($first as $x) {

$sql = mysql_query("select * from contacts where first like '%$x%'"); 

while ($row = mysql_fetch_array($sql)){
echo 'ID: '.$row['id'];
echo '<br/> First Name: '.$row['first'];
echo '<br/> Last Name: '.$row['last'];
echo '<br/> Phone: '.$row['phone'];
echo '<br/><br/>';
}	
}

 

You have a great weekend.

 

Hopefully this can help others as well.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.