0

im using a search form to serach my sql database to return on the requiered infromation but it seems to retive all the info, what i wnat the serach to do is if some1 types in say nokia and n97 for it to return just the results for nokia n97 and not all the nokia phones like its doin now this may be simple for some1 but its been doing my head for days any help would be appreciated my codes is below.

FORM action="form2.php" method="post">
    <P>
     Enter make of phone: <INPUT type="text" name="make"><br>
     Enter model of phone: <INPUT type="text" name="model">
    </P>
    <P>
     <INPUT type="submit" value="Search">
    </P>
   </FORM>

<

<?
    $dbServer=mysql_connect("localhost","0924472","402hqo");
    if (!$dbServer) {echo "Failed to connect to MySQL"; exit; }
    
    mysql_select_db("db0924472",$dbServer);
    
    $sql ="SELECT * FROM mobilephones";
    $sql.=" WHERE make=\"".$_POST["make"]."\"";  // the space before the WHERE is critical
    

    $queryResult=mysql_query($sql);
    
    if (mysql_error())
    {
      echo "Problem with Query<BR>";
      echo "The following error message was returned from MySQL:<BR>";
      echo mysql_error();
      exit;
    }
    
    if (mysql_num_rows($queryResult)==0)
    {
      echo "No phones were found please try again.";
    }
    else
    {   
      while ($dbRecord=mysql_fetch_array($queryResult))
      {
        echo "Phones Found: ".$dbRecord["make"].", ".$dbRecord["model"].", ".$dbRecord["camera"].", ".$dbRecord["bluetooth"]."<BR>";
      }
    }
 ?>
2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by ryan-t
0

seems to be line 8 which isn't designed to handle both.

correct code i belive is

$sql.=" WHERE make=\"".$_POST["make"]."\" AND model=\"".$_POST["model"]."\"";
0

thanks that works great now, if i wanted to add to this to say if someone only types in the phone model and for it to return all phones of that model how would i do that i think i would need an else statemnt but im not sure

0

yeah, ideal code would be

<? if(empty($_POST['make'])){
// insert the code you want to execute when 'make' is empty 
}

else{
// insert code for everything else
}

Also, as an after thought. Using text that was user imputed in a mysql quesry can be a big security flaw allowing users to execute mysql querys on your database. Best thing to do is

define a variable with the $_POST results like so

$make = mysql_real_escape_string($_POST);
$model = mysql_real_escape_string($_POST);

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.