致命错误:调用101行中的未定义函数getRecords():C:\xampp\htdocs\Employees.php [英] Fatal error: Call to undefined function getRecords() in C:\xampp\htdocs\Employees.php on line 101

查看:181
本文介绍了致命错误:调用101行中的未定义函数getRecords():C:\xampp\htdocs\Employees.php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读过这个错误,但是没有一个答案似乎适用于我的具体问题。我的代码的目的是3倍。我正在创建填充数据库的表单。然后在同一页上,我希望能够用第二种形式搜索数据库,并用第三种形式删除记录。我一次一个地处理这些问题,所以我在下面发布的代码是不完整的,但表单都在那里。如果您想知道为什么会有删除表单并且没有删除代码。 :-P。任何人都可以看到我在做我的函数,buildQuery不正确吗?我相信这是getRecords问题的关键。或者不是?

I have read about this error, but none of the answers seem to apply to my specific issue. The purpose of my code is 3-fold. I am creating a form that populates a database. Then on the same page I want to be able to search the database with a 2nd form and delete records with a 3rd form. I'm working on these issues one at a time, so the code I am posting below is incomplete, but the forms are all there. In case you are wondering why there is a delete form and no code for deleting. :-P. Can anyone see what I am doing incorrectly with my function, buildQuery? I believe that is the key to my problem with getRecords. Or not?

<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>


推荐答案

PHP无法找到您的getRecords()函数。你有没有包含这个函数定义的文件?

PHP cannot locate your getRecords() function. Have you included the file that this function is defined in?

编辑:

你发布的数据,只是一般的代码清洁。最好是直接使用mysql提供的函数,而不是将它们包装在仅适用于某种情况的函数中。

You should really look into securing your posted data, and just general code cleanliness. It's better to use the functions mysql provides directly, instead of wrapping them in functions that are only usable for one situation.

并且:为什么在这个世界中,你构建了整个雇员信息表每次,或者至少检查它是否存在?这应该是你曾经做过的事,而忘记了。然后删除那些代码,因为它是令人困惑的。

And: why in the world are you building your entire employeeinfo table each time, or at least checking if it exists? This should be something you do once, and forget about. Then delete that code, because it is confusing.

您应该在潜入之前思考这一切应该如何合理地工作。这基本上是一个员工管理系统?看起来您希望能够:添加新员工,搜索员工,编辑员工以及删除员工。这是一个基本的实现,它缺少添加员工的功能。我没有测试过这个,但我希望它能指出你的方向:

You should think about how this all should logically work before you dive in. This is basically an employee management system? Looks like you want to be able to: Add new employees, search for employees, edit employees, and delete employees. Here is a basic implementation, its missing the feature to add an employee. I haven't tested this, but I hope it points you in the right direction:

    <?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:

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:

/* 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:

/* 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:

   /*footer.php */

</body>
</html>

/* End footer.php */

,而这种事情应该实现成一个php类。
这是使用PDO,所以如果你的数据库细节有变化,你只需要修改dbfactory.php,就完成了。

Again this is still basic, and this kind of thing should be implemented into a php Class. This is using PDO, so if your db details ever change, you just have to alter dbfactory.php, and you are done.

如果我可以去回去并改变一件关于开始学习PHP的事情,那就是学习PDO,而不是像你正在使用的那样的解析mysql查询函数。

If I could go back and change one thing about starting to learn PHP, it would be to learn PDO instead of the depreceated mysql query functions like you are using.

这绝不是一个像我说的那样,完美的实现应该全部归类,逻辑与呈现分离;但这是一个开始!

This is by no means a perfect implementation, like I said, it should all be classed, and logic separated from presentation; but it is a start!

快乐学习!

这篇关于致命错误:调用101行中的未定义函数getRecords():C:\xampp\htdocs\Employees.php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆