2011-10-24 19 views
0

このエラーについては読んだことがありますが、回答は私の特定の問題に該当しないようです。私のコードの目的は3倍です。私はデータベースに値を設定するフォームを作成しています。同じページで、私は2番目のフォームでデータベースを検索し、3番目のフォームでレコードを削除したいと考えています。私は一度に1つずつこれらの問題に取り組んでいるので、私が下に投稿しているコードは不完全ですが、フォームはすべてそこにあります。あなたが削除フォームがあり、削除のためのコードがない理由が不思議に思う場合に備えて。 :-P。誰かが私の関数buildQueryで間違っていることを見ることができますか?私はそれがgetRecordsの問題の鍵だと信じています。か否か?致命的なエラー:行101のC: xampp htdocs Employees.phpで未定義の関数getRecords()を呼び出す

<html> 
<body> 

<?php error_reporting (E_ALL^E_NOTICE); 
$keyword = $_GET['keyword']; ?> 

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

if (mysql_query("CREATE DATABASE IF NOT EXISTS employees",$con)) 
    { 
    echo "Database created"; 
    } 
else 
    { 
    echo "Error creating database: " . mysql_error(); 
    } 

mysql_select_db("employees", $con); 
$sql = "CREATE TABLE employeeinfo 
(
personID int NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(personID), 
FirstName varchar(15), 
LastName varchar(15), 
Phone varchar(15), 
Email varchar(15), 
Department varchar(15), 
Position varchar(15), 
)"; 

mysql_query("INSERT INTO employeeinfo (FirstName, LastName, Phone, Email, Department, Position) 
VALUES ('firstname', 'lastname', 'phone', 'email', 'department', 'position')"); 

mysql_query($sql,$con); 

     function buildQuery() { 

     $keyword = $_GET['keyword']; 

     $sql = "SELECT * from employeeinfo WHERE 
       (
       firstname LIKE '%$keyword%' 
       OR 
       lastname LIKE '%$keyword%' 
       OR 
       phone LIKE '%$keyword%' 
       OR 
       email LIKE '%$keyword%' 
       OR 
       department LIKE '%$keyword%' 
       OR 
       position LIKE '%$keyword%' 
       )"; 

     return $sql; 

     mysql_close($con); 

     } ?> 

     <form action="Employees.php" method=get> 
     <fieldset> 
     <legend>Submit Employee Info</legend> 
     Firstname: <input type="text" name="firstname" /> 
     Lastname: <input type="text" name="lastname" /> 
     Phone: <input type="text" name="phone" /> 
     Email: <input type="text" name="email" /> 
     Department: <input type="text" name="department" /> 
     Position: <input type="text" name="position" /> 
     <input type=submit name=submit value=Submit /> 
     </fieldset> 
     </form> 

     <form action="Employees.php" method=get> 
     <fieldset> 
     <legend>Search Employee Info</legend> 
     <label for="keyword">Enter Keyword</label> 
     <input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>" /> 
     <input type=submit name=submit value=Search /> 
     </fieldset> 
     </form> 

     <form action="Employees.php" method=get> 
     <fieldset> 
     <legend>Delete Employee Info</legend> 
     <label for="keyword">Enter Keyword</label> 
     <input id="keyword" name="keyword" value="<?php echo "$keyword"; ?>" /> 
     <input type=submit name=submit value=Delete /> 
     </fieldset> 
     </form> 

     <? 

       $query = buildQuery(); 

       $records = getRecords($query); //error is in this line 

       while($row = mysql_fetch_array($records)){ ?> 

     <table> 

     <tbody> 
     <table border='1'> 

     <tr> 
     <td><?= $row['firstname']; ?></td> 
     <td><?= $row['lastname']; ?></td> 
     <td><?= $row['phone']; ?></td> 
     <td><?= $row['email']; ?></td> 
     <td><?= $row['department']; ?></td> 
     <td><?= $row['position']; ?></td> 
     <td><a href="Employees.php">Return to Search</a></td> 
     </tr> 

     <? } 

     ?> 

</tbody> 

</table> 

</body> 
</html> 
+0

「getRecords」ではなく「mysql_query」を意味すると思います – jeroen

+0

ありがとうございます。私はそれを調べます。 – CherylAnnCE

答えて

2

PHPはgetRecords()関数を見つけることができません。この関数が定義しているファイルを含めましたか?

編集:

あなたが本当にあなたのポストされたデータ、およびちょうど一般的なコードのクリーン度を確保になっているはずです。 mysqlが提供する関数を、ある状況でのみ使用できる関数でラップするのではなく、直接使用する方がよいでしょう。

:なぜ世界中で、毎回employeeinfoテーブル全体を構築しているのでしょうか、それとも少なくともそれが存在するかどうかを確認していますか?これはあなたが一度やることで、忘れるべきことです。混乱しているので、そのコードを削除してください。

ダイビングを始める前に、このすべてが論理的にどのように機能すべきかを考える必要があります。これは基本的に従業員管理システムですか?新しい従業員を追加し、従業員を検索し、従業員を編集し、従業員を削除することができるように見えます。ここには、基本的な実装があり、従業員を追加する機能がありません。私はこれをテストしていませんが、私はそれが正しい方向にあなたを指して願っています:

<?php 
/* Employees.php */ 

include('dbfactory.php'); 
include('header.php'); 



if(isset($_GET['do']) && (!empty($_GET['do']))){ 

    switch($_GET['do']){ 

     case 'search': 
      //The form action is appended with a query string, so we can handle multiple cases in process.php 
      ?> 
       <form action="process.php?do=runsearch" method="POST"> 
       <fieldset> 
       <legend>Search Employee Info</legend> 
       <label for="keyword">Enter Keyword</label> 
       <input id="keyword" name="keyword" value="" /> 
       <input type="submit" name="submit" value="Search" /> 
       </fieldset> 
       </form> 
      <?php 


     break; 

     case 'edit': 
      //Make sure that the employee id has been set! 
      if(isset($_GET['eid']) && (!empty($_GET['eid']))){ 

       //Get the DB connection 
       $db = ConnectionFactory::getFactory()->getConnection(); 

       //Set up the query with a ? placeholder 
       $sql = "Select * from employeeinfo WHERE personid = ? LIMIT 1"; 

       $stmt = $db->prepare($sql); 
        //Bind the question mark with the Employee ID, as an Integer ONLY 
        $stmt->bindParam(1, $_GET['eid'], PDO::PARAM_INT); 

        $stmt->execute(); 


       /* Get an array of the result */ 
       $result = $stmt->fetch(PDO::FETCH_ASSOC); 

       /* Make an array of friendly names associated with the mysql fields */ 
       if(count($result) > 0){ 
        //Set up friendly names: 
        $fnames = array('firstname' => 'First Name', 
           'lastname' => 'Last Name', 
           'phone' => 'Phone Number', 
           'email' => 'Email Address', 
           'department' => 'Department', 
           'position' => 'Position'); 

        /* Start the form, and make a hidden field with the employee id we want to edit.*/ 
        ?> 
        <form action="process.php?do=saveedits" method="POST"> 
        <input type="hidden" name="personid" value="<?=$result['personid']?>" /> 
        <?php 

        /* Unset the person id, because we already used it */ 
        unset($result['personid']); 

        //*Fill the fields with values from the database, if a friendly name is found, it will be used as the label*/ 
        foreach($result as $key => $value){ 
         ?> 
         <label for="<?=$key?>"><?=(isset($fnames["$key"]) ? $fnames["$key"] : $key)?></label> 
         <input id="<?=$key?>" name="<?=$key?>" value="<?=$value?>" /> 
         <br> 
         <?php      
        } 

        ?> 
        <input type="submit" value="Modify Employee" > 
        </form> 
        <?php 



       } 
       else{ 
        /* Couldnt find that employee in the DB */ 
        ?> 
        <h2>Error, Employee Not Found</h2> 
        <?php 
        } 
      } 

     break; 

     case 'new': 
      //Make sure that the employee id has been set! 

       /* Make an array of friendly names associated with the mysql fields */ 

        //Set up friendly names: 
        $fnames = array('firstname' => 'First Name', 
           'lastname' => 'Last Name', 
           'phone' => 'Phone Number', 
           'email' => 'Email Address', 
           'department' => 'Department', 
           'position' => 'Position'); 

        /* Start the form, and make a hidden field with the employee id we want to edit.*/ 
        ?> 
        <form action="process.php?do=savenew" method="POST">  
        <?php 

        //*Fill the fields with values from the database, if a friendly name is found, it will be used as the label*/ 
        foreach($fnames as $key => $value){ 
         ?> 
         <label for="<?=$key?>"><?=$value?></label> 
         <input id="<?=$key?>" name="<?=$key?>" /> 
         <br> 
         <?php 

        } 

        ?> 
        <input type="submit" value="Create New Employee" > 
        </form> 
        <?php 


     break; 


     case 'delete': 

      if(isset($_GET['eid']) && (!empty($_GET['eid']))){ 
      $db = ConnectionFactory::getFactory()->getConnection(); 

        /* Make sure this person exists, and get their info */ 
        $sql = "Select * from employeeinfo WHERE personid = ?"; 

        $stmt = $db->prepare($sql); 
         /* Same as above */ 
         $stmt->bindParam(1, $_GET['eid'], PDO::PARAM_INT); 

         $stmt->execute(); 



        $result = $stmt->fetch(PDO::FETCH_ASSOC); 

        if(count($result) > 0){ 
        /* Ask to confirm the delete */ 
         ?> 
         <h2>Are you sure you want to delete <?=$result['firstname']?> <?=$result['lastname']?>'s Records?</h2> 
         <a href="process.php?do=confirmdelete&eid=<?=$result['personid']?>">Yes, Confirm Delete!</a> 
         <?php 
        } 
        else{ 
         ?> 
         <h2>Error, Employee Not Found</h2> 
         <?php 
         } 

      } 
      break; 



    } 
} 
else{ 
//List employees 



$db = ConnectionFactory::getFactory()->getConnection(); 


        $sql = "SELECT * from employeeinfo"; 

        $stmt = $db->prepare($sql); 
        $res = $stmt->execute(); 


        /* Make a table with the results and headings */ 
        if($res){ 
         ?> 
          <table> 
          <tr> 
          <td>First Name</td> 
          <td>Last Name</td> 
          <td>Email</td> 
          <td>Phone</td> 
          <td>Department</td> 
          <td>Position</td> 
          <td>Actions</td> 
          </tr> 
         <?php 
        while($result = $stmt->fetch(PDO::FETCH_ASSOC)){ 
         ?> 
          <tr> 
          <td><?=$result['firstname']?></td> 
          <td><?=$result['lastname']?></td> 
          <td><?=$result['email']?></td> 
          <td><?=$result['phone']?></td> 
          <td><?=$result['department']?></td> 
          <td><?=$result['position']?></td> 
          <td><a href="employees.php?do=edit&eid=<?=$result['personid']?>">Edit</a>&nbsp;&nbsp; 
           <a href="employees.php?do=delete&eid=<?=$result['personid']?>">Del</a> 
          </td> 
          </tr> 
         <?php 
         }     
         ?> 
          </table> 
         <?php   

         } 


} 

include('footer.php'); 
/* End Employees.php */ 
?> 

Process.php:

<?php 
/* Process.php */ 


// Bind the parameter 


include('dbfactory.php'); 
include('header.php'); 


if(isset($_GET['do']) && (!empty($_GET['do']))){ 

    switch($_GET['do']){ 

     case 'runsearch': 

       if((isset($_POST['keyword'])) && (!empty($_POST['keyword']))){ 

       /* You have to put the % signs in beforehand with PDO */ 
        $keyword = "%".$_POST['keyword']."%"; 

        $db = ConnectionFactory::getFactory()->getConnection(); 


        $sql = "SELECT * from employeeinfo WHERE 
        firstname LIKE ? 
        OR 
        lastname LIKE ? 
        OR 
        phone LIKE ? 
        OR 
        email LIKE ? 
        OR 
        department LIKE ? 
        OR 
        position LIKE ?"; 

        $stmt = $db->prepare($sql); 

        /* There are 6 placeholders, so we need to loop 6 times, binding the new placeholder each time */ 
        for($i=1; $i<=6; $i++){ 
         $stmt->bindParam($i, $keyword, PDO::PARAM_STR); 
        }     
        $res = $stmt->execute(); 


        /* Make a table with the results and headings */ 
        if($stmt->rowCount() > 0){ 
         ?> 
          <table> 
          <tr> 
          <td>First Name</td> 
          <td>Last Name</td> 
          <td>Email</td> 
          <td>Phone</td> 
          <td>Department</td> 
          <td>Position</td> 
          <td>Actions</td> 
          </tr> 
         <?php 

        while($result = $stmt->fetch(PDO::FETCH_ASSOC)){ 
         ?> 
          <tr> 
          <td><?=$result['firstname']?></td> 
          <td><?=$result['lastname']?></td> 
          <td><?=$result['email']?></td> 
          <td><?=$result['phone']?></td> 
          <td><?=$result['department']?></td> 
          <td><?=$result['position']?></td> 
          <td><a href="employees.php?do=edit&eid=<?=$result['personid']?>">Edit</a>&nbsp;&nbsp; 
           <a href="employees.php?do=delete&eid=<?=$result['personid']?>">Del</a> 
          </td> 
          </tr> 
         <?php 
         }     
         ?> 
          </table> 
         <?php   

        } 
        else{ 
        ?><h2>No Results Found!<?php 
        } 

       } 
       else{ 
       ?><h2>No Keyword Set!<?php 
       } 



     break; 

     case 'saveedits':  

      /* Array of the fields we expect to be Posted */ 
      $required = array('personid' => 'Employee Id', 
           'firstname' => 'First Name', 
           'lastname' => 'Last Name', 
           'phone' => 'Phone Number', 
           'email' => 'Email Address', 
           'department' => 'Department', 
           'position' => 'Position'); 

      /* Make sure all the fields have been posted */ 
      $good = true; 
      foreach($required as $field => $value){ 
       if(!isset($_POST[$field])) 
        $good = false;  
      } 

      if($good){ 

       $db = ConnectionFactory::getFactory()->getConnection(); 
       /* Have to temporarily store the personid in a temp variable, and remove it from the array */ 
       $pid = $_POST['personid']; 
       unset($_POST['personid']); 
       $posted = $_POST; 

       /* Change this : firstname to : `firstname`=:firstname, etc, etc Runs over the whole arraay */ 
       $params = join(", ", array_map(
       function($col) { 
       return "`".preg_replace("/`/u","``",$col)."`=".":".preg_replace("/[`\s]/u","",$col);}, 
       array_keys($posted))); 

       /* Put the personid back into the posted array, so we can use it again. */ 
       $posted['personid'] = $pid; 

       $stmt = $db->prepare("UPDATE `employeeinfo` SET {$params} WHERE `personid`=:personid"); 
       /* Use the whole post array to execute looks like: field => value */ 
       $stmt->execute($posted); 

       if($stmt->rowCount() > 0){ 
        ?><h2>Employee Updated!</h2><?php 
       } 
       else{ 
        ?><h2>Error! Could Not Update Employee!</h2><?php 
       } 
      } 
      else{ 
      print_r($_POST); 
      print_r($required); 
       ?><h2>Form Error! Required fields not set!</h2><?php 
      } 


     break; 

     case 'savenew':  

      /* Array of the fields we expect to be Posted */ 
      $required = array('firstname' => 'First Name', 
           'lastname' => 'Last Name', 
           'phone' => 'Phone Number', 
           'email' => 'Email Address', 
           'department' => 'Department', 
           'position' => 'Position'); 

      /* Make sure all the fields have been posted */ 
      $good = true; 
      foreach($required as $field => $value){ 
       if(!isset($_POST[$field])) 
        $good = false;  
      } 

      if($good){ 

       $db = ConnectionFactory::getFactory()->getConnection(); 
       /* Have to temporarily store the personid in a temp variable, and remove it from the array */ 
       $posted = $_POST; 



        $columns = join(",", array_map(
        function($col) { return "`".preg_replace("/`/u","``",$col)."`";}, 
        array_keys($posted))); 

        $params = join(",", array_map(
        function($col) { return ":".preg_replace("/[`\s]/u","",$col);}, 
        array_keys($posted))); 


        $query = "INSERT INTO `employeeinfo` ({$columns}) VALUES ({$params})"; 

        $stmt = $db->prepare($query); 
        $stmt->execute($posted); 

       if($stmt->rowCount() > 0){ 
        ?><h2>Employee Created!</h2><?php 
       } 
       else{ 
        ?><h2>Error! Could Not Create Employee!</h2><?php 
        print_r($stmt->errorInfo()); 
       } 
      } 
      else{ 
       ?><h2>Form Error! Required fields not set!</h2><?php 
      } 


     break; 

     /* Pretty Self Explanatory */ 
     case 'confirmdelete': 

       if(isset($_GET['eid']) && (!empty($_GET['eid']))){ 

       $db = ConnectionFactory::getFactory()->getConnection(); 


        $sql = "Delete from `employeeinfo` WHERE personid = ?"; 


        $stmt = $db->prepare($sql); 

         $stmt->bindParam(1, $_GET['eid'], PDO::PARAM_INT); 

         $stmt->execute(); 

         if($stmt->rowCount() > 0){ 
         ?><h2>Employee Deleted!</h2><?php 
         } 
         else{ 
         ?><h2>Error! Could Not Delete Employee!<br></h2><?php 
         print_r($stmt->errorInfo()); 
         } 
       } 
       else{ 
       ?><h2>Error! No Employee By That Id!</h2><?php 
       } 

     break; 


    } 
} 
else{ 
//Error nothing to do! 
} 

/* End process.php: */ 
?> 

Dbfactory.php:

/* dbfactory.php: */ 
    <?php 
Class ConnectionFactory 
{ 
    private static $factory; 
    public static function getFactory() 
    { 
     if (!self::$factory) 
      self::$factory = new ConnectionFactory; 
     return self::$factory; 
    } 

    private $db; 

    public function getConnection() { 
     if (!isset($db)){ 

      try{ 
      //Make sure to fill out these values 
      $db = new PDO('mysql:dbname=YOURDATABASENAME;host=YOURDATABASEADDRESS', 'USERNAME', 'PASSWORD'); 
      return $db; 
      } 
      catch(PDOException $e) { 
      echo 'DB Error: '. $e->getMessage(); 
      } 

     } 
    } 
} 
?> 
/* End dbfactory.php: */ 

header.phpの:

/* Header.php: */ 



<html> 
<head> 
<style type="text/css"> 

td{ 
border:1px solid; 
border-radius:3px; 
padding:4px; 
} 
</style> 
</head> 
<body> 
<a href="employees.php">Manage Employees</a> - <a href="employees.php?do=search">Search Employees</a> - <a href="employees.php?do=new">Add Employee</a> 
<br> 
<br> 

/* End header.php */ 

Footer.php:

/*footer.php */ 

</body> 
</html> 

/* End footer.php */ 

これもやはり基本的なことですが、この種のことはphpクラスに実装する必要があります。 これはPDOを使用しているので、dbの詳細が変更された場合は、dbfactory.phpを変更するだけで完了です。

もし私がPHPを学び始めるということを一つ前に戻すことができれば、あなたが使っているようなdepreceated mysqlクエリ関数の代わりにPDOを学ぶことになります。

これは決して完璧な実装ではなく、私が言ったように、それはすべて分類され、ロジックはプレゼンテーションから分離されている必要があります。しかしそれはスタートです!

ハッピーラーニング!

+0

ありがとうございます。それを見てください。 – CherylAnnCE

+0

うわー!ありがとう、ベン!私はPDOを学びます。私の質問に徹底的に答えてくれてありがとう!くすぐることがたくさんある。 – CherylAnnCE

+0

employeeinfoテーブルについての良い点。それはテーブルを作成していなかったが、なぜ(私は最後にコンマを残したのか)わかったら、テーブルは正常に作成され、コードを削除した。 – CherylAnnCE

関連する問題