4 Replies - 1425 Views - Last Post: 29 December 2011 - 08:14 AM Rate Topic: -----

#1 Dark Samus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 03-January 11

Search function for MySQL tables

Posted 28 December 2011 - 06:33 AM

I’m trying to generate a script that will allow the user to search for patient details, by using a drop down menu to select the table and then use the text box to search for the patients first name (first_name), which will then return each patient with ten specified name and the patient id (pid).

But I get this error:

“Notice: Undefined variable: sql in C:\xampp\htdocs\coursework1\website\search.php on line 23
Query was empty”


Now, my table has been set up using a .sql file via PHPAdmin, as opposed to creating the tables using PHP functions.

I have tried swapping around the variable names such as $result and $sql. This does not seem to work, as I get the same error.

Am I on the right trick? If not what should I do and how would this be implemented?

Here is my code. The first code snippet is the search.php file, which performs the search. The DBPatients file, has functions for update,delete and a connection to the database. The functions have been tested and work correctly.


Search.php
<?php include 'DBPatients.php';   //import the class in this web page  ?> 

<?php 
error_reporting(E_ALL);
$search_output ="";
ini_set('display_errors', '1');

//This processes the search query 
if(isset($_POST['searchquery'])&& $_POST ['searchquery'] != ""){
    
    $searchquery = preg_replace ('#[^a-z 0-9?()!]#i','',$_POST['searchquery']);
    if ($_POST ['filter1'] == "Whole Site"){
    }
    
    /// this provides a search for the patient via the drop down, whish is nameed as filter1
    elseif ($_POST ['filter1'] == "Patients"){
        $sql = "SELECT pid,first_name AS name FROM patients WHERE first_name LIKE '%Searchquery%' OR
            last_name LIKE '%searchquery%'";
    }
   
}

   $result = mysql_query($sql) or die (mysql_error());
   $count = mysql_num_rows($result);
   if ($count > 1) {
   echo "";
   
   $search_output .= "<hr />$count results for<strong>$searchquery</strong><hr />$sql<hr />";
   while($row = mysql_fetch_array ($result)){
       $pid =$row["pid"];
       $name=$row["name"];
       $search_output .="Item ID: $pid -$name<br />";
   }
   } else {
       $search_output = "<hr\> () 0 results for <strong>$searchquery</strong><hr />$sql";
       
   }
 
    
    

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Owner Example</title>
</head>

<body>
         <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
       Search: <input name="searchquery" type="text" size="80" maxlength="88"/>
       <input name="mybtn" type="submit"/>
       <br /> <br />
       <select name="filter1">
           <option value="patients">Patients</option> 
       </select>
    </form>
    <div>
       <?php echo $search_output; ?>
    </div>
  </body>
 </html>



DBPatients.php
<?php 
require("db_config.php");

class DBPatients {
    /* DB connection handle*/
    private $conn;

     function openDB()
    {
      $this->conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
         if(!$this->conn)
        {
          die("SQL Connection error: " . mysql_error());
        }
         $db_selected = mysql_select_db(DB_NAME,$this->conn);
         if(!$db_selected)
        {
         die("SQL Selection error: " . mysql_error());
        }
     }

     function closeDB()
    {
     mysql_close($this->conn);
    }

     function insert_patient($pid,$first_name,$last_name,$address,$phone)
    {

      $esc_first_name = mysql_real_escape_string($first_name,$this->conn);
      $esc_last_name = mysql_real_escape_string($last_name,$this->conn);
      $esc_addr = mysql_real_escape_string($address,$this->conn);
      $esc_phone = mysql_real_escape_string($phone,$this->conn);
      


      $sql="INSERT INTO patients (pid ,first_name,last_name, address,phone)
            VALUES ('{$pid}', '{$esc_first_name}','{$esc_last_name}', '{$esc_addr}','{$esc_phone}')";
      $result=mysql_query($sql,$this->conn);

       if(!$result)
      {
       die("SQL Insertion error: " . mysql_error());
      }
       else
      {
       $numofrows = mysql_affected_rows($this->conn);
       return $numofrows;
      }
    }
    
    
     function delete_patient($pid)
    {
    
      $esc_pid = mysql_real_escape_string($pid,$this->conn);
      
      $sql="delete from patients where pid ='{$esc_pid}'";
      $result=mysql_query($sql,$this->conn);

       if(!$result)
      {
       die("SQL Update error: " . mysql_error());
      }
       else
      {
       $numofrows = mysql_affected_rows($this->conn);
       return $numofrows;
      }
    }

    function update_patient($pid,$first_name,$last_name,$address,$phone)
    {

      $esc_first_name = mysql_real_escape_string($first_name,$this->conn);
      $esc_last_name = mysql_real_escape_string($last_name,$this->conn);
      $esc_addr = mysql_real_escape_string($address,$this->conn);
      $esc_phone = mysql_real_escape_string($phone,$this->conn);

      $sql="update patients SET address='{$esc_addr}', first_name='{$esc_first_name}'
      , last_name='{$esc_last_name}', phone='{$esc_phone}' 
      where pid='{$pid}'";
      $result=mysql_query($sql,$this->conn);

       if(!$result)
      {
       die("SQL Update error: " . mysql_error());
      }
       else
      {
       $numofrows = mysql_affected_rows($this->conn);
       return $numofrows;
      }
    }
    
     function __construct()
    {
      //Empty Constructor
    }
}
?>



Is This A Good Question/Topic? 0
  • +

Replies To: Search function for MySQL tables

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 934
  • View blog
  • Posts: 2,327
  • Joined: 15-February 11

Re: Search function for MySQL tables

Posted 28 December 2011 - 06:47 AM

Hey,

A few things you should know...
  • Search.php (line 11) Your regular expression's using parenthesis but they don't surround anything. My guess is you were including them in the range. You must escape special characters when using their literal meaning.
    #\(\)#
    
    This will match ()
  • In your query you're trying to match %Searchquery% but in actual fact it will only return the rows with searchquery in the first or last name and not the value of $searchquery
  • I recommend you upgrade to either MySQLi or PDO. They both offer Prepared Statements which will protect your database from SQL injections. Here's a tutorial demonstrating how to add items to select element from your query results. Simple Solutions: Populating Select Element Using DOM

Was This Post Helpful? 0
  • +
  • -

#3 Dark Samus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 03-January 11

Re: Search function for MySQL tables

Posted 28 December 2011 - 08:29 AM

View Postcodeprada, on 28 December 2011 - 06:47 AM, said:

Hey,

A few things you should know...
  • Search.php (line 11) Your regular expression's using parenthesis but they don't surround anything. My guess is you were including them in the range. You must escape special characters when using their literal meaning.
    #\(\)#
    
    This will match ()
  • In your query you're trying to match %Searchquery% but in actual fact it will only return the rows with searchquery in the first or last name and not the value of $searchquery
  • I recommend you upgrade to either MySQLi or PDO. They both offer Prepared Statements which will protect your database from SQL injections. Here's a tutorial demonstrating how to add items to select element from your query results. Simple Solutions: Populating Select Element Using DOM



Thanks for the reply and a link to your tutorial. That was a good tutorial, but I am trying to use a drop down that allows a user to select the desired table and then search for the name via a text box. That tutorial could come in handy for something else though.

Yeah, line 11 doesn't concern me as it is more for character validation.Yeah I should use MySQLi or PDO, but I have to use MySQL instead. As for the searchquery function, I don't get any results, because of the error message that I posted.

This video is very similar as to what I am trying to achieve.
http://www.youtube.c...h?v=DVS4qoB98U8


I am still stuck as to what to do.. But thank you for taking the time to post your insightful tips. :)
Was This Post Helpful? 0
  • +
  • -

#4 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2484
  • View blog
  • Posts: 8,517
  • Joined: 08-August 08

Re: Search function for MySQL tables

Posted 28 December 2011 - 09:16 AM

if ($_POST ['filter1'] == "Whole Site"){
	// $sql is NOT defined in this case.
} elseif ($_POST ['filter1'] == "Patients"){
		$sql = "SELECT pid,first_name AS name FROM patients WHERE first_name LIKE '%Searchquery%' OR
				last_name LIKE '%searchquery%'";
}


Was This Post Helpful? 0
  • +
  • -

#5 Dark Samus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 03-January 11

Re: Search function for MySQL tables

Posted 29 December 2011 - 08:14 AM

Ok, after futher rummaging through Youtube, I got the code working.

Thanks for the reply CTphpnwb though. I appreciate it. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1