PHP form returns all MYSQL data, help!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jamesmoore
    New Member
    • Jan 2011
    • 47

    #1

    PHP form returns all MYSQL data, help!

    Hi there,

    My code works fine and retrieves information from my database BUT when the search form is empty and I click submit all the information from my database appears.

    How can I have it so when submit is clicked nothing happens or a message appears like "Nothing entered"


    Thanks a lot!

    James

    Code:
    <html>
    <body>
    James' New Site
    <form action="seaside.php" method="post">
    <input type="text" name="search"><br>
    <input type="submit">
    </form>
    <hr width="100%"></hr>
    </body>
    </html>
    <?php
      $search = "%" . $_POST["search"] . "%";
     
      mysql_connect ("", "", "");
      mysql_select_db ("");
     
      $query = "SELECT name,msg FROM contact WHERE name LIKE '$search'";
      $result = mysql_query ($query);
      if ($result) {
        while ($row = mysql_fetch_array ($result)) {
          echo "<br>$row[0]</br>";
          echo $row[1];
        }
      }
    ?>
    Last edited by Niheel; Aug 15 '11, 08:31 PM.
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    You need an if statement.

    Code:
    if($_POST['search']) {
    
       do your query here. 
    
    }
    this ensures when you come to the page, your don't run the query but only when the form is submitted.

    WARNING: your code is hackable!

    Make sure you clean $search variable for bad content before submitting it to the db. run mysql_real_esca pe_string() on it. (see php manual)

    if I enter

    Code:
    '; DELETE FROM contact WHERE '1' = '1
    into your search box, I can delete everything from the contact table.

    If you don't believe me, try it.


    Dan

    Comment

    • jamesmoore
      New Member
      • Jan 2011
      • 47

      #3
      Hi Dan,

      thanks for the help!

      Where abouts in my code do I include your code? Do I have to replace a part of my code with your code?

      And thanks for the heads up! Is there a simple code to include to protect it?
      Or can you recommend a site that will provide me with the code to protect it?

      Thanks again!

      James

      Comment

      Working...