1

What will be the syntax if I want to list a person with an address like the one inputted by the user?Here is my code, please help. The form input would be address. I want to do something like this: http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html

 <?php
       $con = mysql_connect("localhost","root","");
       if (!$con)
        {
       die('Could not connect: ' . mysql_error());
      }

       mysql_select_db("Hospital", $con);

        $result = mysql_query("SELECT * FROM nais WHERE ADDRESS='{$_POST["address"]}'");

       echo "<table border='1'>
         <tr>
      <th>HospNum</th>
          <th>RoomNum</th>
           <th>LastName</th>
           <th>FirstName</th>
      <th>MidName</th>
            <th>Address</th>
         <th>TelNum</th>
          <th>Nurse</th>
       </tr>";

          while($row = mysql_fetch_array($result))
           {
                 echo "<tr>";
  echo "<td>" . $row['HOSPNUM'] . "</td>";
     echo "<td>" . $row['ROOMNUM'] . "</td>";
     echo "<td>" . $row['LASTNAME'] . "</td>";
  echo "<td>" . $row['FIRSTNAME'] . "</td>";
    echo "<td>" . $row['MIDNAME'] . "</td>";
      echo "<td>" . $row['ADDRESS'] . "</td>";
       echo "<td>" . $row['TELNUM'] . "</td>";
        echo "<td>" . $row['NURSE'] . "</td>";

     echo "</tr>";
   }
     echo "</table>";

      mysql_close($con);
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
user225269
  • 10,743
  • 69
  • 174
  • 251
  • 2
    (*hint*) you don't want someone to search for `1';DROP TABLE nais --` – Gordon Jan 30 '10 at 14:10
  • @Gordon: That wouldn't work with MySQL, right? Nontheless, of course you are right that this code is open for SQL injections... – Franz Jan 30 '10 at 14:15
  • @Franz: I don't see why the SQL Injection provided by Gordon wouldn't work... – Alix Axel Jan 30 '10 at 14:20
  • 4
    @Alix because by default multiple queries are not supported by `mysql_query`. That shouldn't be reason not to sanitize the string though. You could still append other search criteria. – Gordon Jan 30 '10 at 14:35
  • 1
    Not to mention all the `echo $row` calls that forget to `htmlspecialchars`, resulting in XSS. – bobince Jan 30 '10 at 15:39
  • Yup, Gordon is right. And exactly what I meant. And this is of course still bad (the "best" case would be a failed query with possibly the query being dumped - which is a leak of information)... – Franz Jan 30 '10 at 20:27

1 Answers1

4

Try this:

$result = mysql_query("SELECT * FROM nais WHERE ADDRESS LIKE '%" . $_POST['address'] . "%';");

You should also use prepared statements or mysql_real_escape_string(), see SQL Injections.

Community
  • 1
  • 1
Alix Axel
  • 151,645
  • 95
  • 393
  • 500