【问题标题】:Trying to read an instance of an object into a database with PHP尝试使用 PHP 将对象的实例读入数据库
【发布时间】:2012-10-13 18:43:57
【问题描述】:

您好,我正在尝试读取我的对象 person 的实例,使用表单获取其个人详细信息,然后将其放入数据库中。我想我的代码设置了这个人,并连接到数据库好,我只是在处理表单信息并将其读入数据库时​​无法正确处理。任何帮助将不胜感激!

我的表格

    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
       <form action="process.php" method="post">
        First Name: <input type="text" name="firstName" />
        Last Name: <input type="text" name="lastName" />
        Age: <input type="text" name="age" />
        <input type="submit" />
       </form>
    </body>
</html>

我尝试处理它的地方

   <?php
$i = 0;
$firstName = 'firstName';
$lastName = 'lastName';
$age = 'age';
$person = new person ($i,$firstName, $lastName, $age);
$PersonDAO = new PersonDAO();
$dao->insert($person);
?>

我的 DAO

类 PersonDAO 扩展人{ 受保护的 $link;

public function __construct() {
    $host = "localhost";
    $database = "test";
    $username = "root";
    $password = "";

    $dsn = "mysql:host=$host;dbname=$database";

    $this->link = new PDO($dsn, $username, $password);
    $this->link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
}
public function __destruct() {
    $this->link = null;
}

public function insert($person){
    if (!isset($person) && $person != null){
        throw new Exception("Person Required");
    }
    $sql = "INSERT INTO person(firstName, lastName, age)"
    . "VALUES (:firstName, :lastName, :age)";

    $params = array(
        'firstName' => $person->getFirstName(),
        'lastName' => $person->getLastName(),
        'age' => $person->getAge(),
    );

    $stmt = $this->link->prepare($sql);
    $status = $this->execute($params);
    if ($status != true){
        $errorInfo = $stmt->errorInfo();
        throw new Exception("Could Not Add Person: " . $errorInfo[2]);
    }

    $id = $this->link->lastInsertId('person');
    $person->setId($id);


    }

} ?>

我的表单很好,但是当我点击提交时它说 “致命错误:在第 6 行的 /Applications/XAMPP/xamppfiles/htdocs/personProj/process.php 中找不到类 'person'”

有什么想法吗?谢谢

【问题讨论】:

    标签: php sql database forms dao


    【解决方案1】:

    你可能想试试:

    $person = new Person ($i,$firstName, $lastName, $age);
    

    如果类是用大写字母定义的,你也应该用大写字母来调用它。与方法/类调用的情况保持一致总是一个好主意。在许多其他语言(如 Java)中,这是非常严格的(尽管 PHP 在某些情况下可能对此规则松散)。

    【讨论】:

    • @user1180888 类 Person 在您的文件系统上的什么位置?你还记得在 Process.php 脚本的顶部写 require_once('/path/to/Person.php'); 吗?
    • 哦,天哪,我认为这是排序的。虽然现在我收到了这个错误,有什么想法吗?致命错误:在第 35 行的 /Applications/XAMPP/xamppfiles/htdocs/personProj/personDAO.php 中调用未定义的方法 PersonDAO::execute()
    猜你喜欢
    • 2017-02-11
    • 2018-10-11
    • 2013-08-10
    • 1970-01-01
    • 2013-02-27
    • 2017-07-17
    • 2011-03-19
    • 2020-11-03
    • 2021-03-02
    相关资源
    最近更新 更多