I have created a form where the user can search the database, and the result depends on how the user fills out the form. For example, say I have name, address, city, state, and zip field, and the user fills out name and city fields, the results reflect the input. When the form submits all records are displayed.

Here is what I have:

<?php
		if(isset($_POST['submit'])) {
			$sql = mysql_query("SELECT * FROM table WHERE name LIKE '%" . $_POST['name'] . "%'
					   OR address LIKE '%" . $_POST['address'] . "%'
					   OR city LIKE '%" . $_POST['city'] . "%'
					   OR state LIKE '%" . $_POST['state'] . "%'
					   OR zip LIKE '%" . $_POST['zip'] . "%'");
		}
	?>

<table>
			<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
				<tr>
					<td>Name:</td>
					<td><input type="text" name="name" /></td>
				</tr>
				<tr>
					<td>Address:</td>
					<td><input type="text" name="address" /></td>
				</tr>
				<tr>
					<td>City:</td>
					<td><input type="text" name="city" /></td>
				</tr>
				<tr>
					<td>State:</td>
					<td><input type="text" name="state" /></td>
				</tr>
				<tr>
					<td>Zip:</td>
					<td><input type="text" name="zip" /></td>
				</tr>
				<tr>
					<td>&nbsp;</td>
					<td><input type="submit" name="submit" value="Search" /></td>
				</tr>
			</form>
		</table>

	<?php
		if(isset($_POST['submit'])) {
			while($row = mysql_fetch_array($sql)) {
				echo $row['name'] . "<br />";
			}
		}	
	?>

Any suggestions what I could do? Thanks in advanced.

    what if i didn't fill all the fields ?
    try to add just those fields dynamically where there is available keyword.

    for example:

    <?php
    function pa( $index )
    {
        if ( isset( $_POST[$index] ) AND strlen( $_POST[$index] ) > 0 )
            return true;
    } 
    
    function field( $fieldname , $postindex )
    {
        return $fieldname . " like '%" . mysql_real_escape_string( $_POST[$postindex] ) . "%'";
    } 
    
    // include here mysql connection 
    
    
    $sql = "select * from tablename ";
    $query = array();
    
    // conditions
    if ( pa( 'name' ) )
        $query[] = field( 'name' , 'name' );
    if ( pa( 'address' ) )
        $query[] = field( 'address' , 'address' );
    // conditions ...
    
    // add the $query conditions to your main query
    if ( count( $query ) > 0 ) // you have conditions!
        $sql . = ' WHERE ' . implode( ' OR ', $query );
    echo $sql; // test and run this string
    
    ?>
      Write a Reply...