在pdo pql语句中使用对象属性值

时间:2014-12-19 14:50:06

标签: php mysql pdo

我对此很新。我希望有人能告诉我为什么下面的代码不起作用。

我正在尝试将数据从Ajax请求发布到php脚本。我正在将值作为“用户”对象的属性加载。我希望然后使用它们来调用数据库函数,但我无法弄清楚为什么我不能在PDO语句中使用对象属性值。他们未定义......

由于

    <?php

class Userclass{
    public $id;
    public $forename;
    public $surname;
    public $greeting = "Mr";
    public function f(){
        call_user_func("dbinsert");
        }
};


try {
    $user = new Userclass;
    $user->id = $_POST["id"];
    $user->forename = $_POST["forename"];
    $user->surname = $_POST["surname"];
    $user->f();
} catch (Exception $e) {
    echo "failed";
    exit;
}


function dbinsert(){
    Require("dbconnect.php");

        try {
            $sql = "INSERT INTO testtable (id, forename, surname)
                VALUES (:id, :forename, :surname)";    
            $insert = $db->prepare($sql);
            $insert->bindValue(':id', $user->id);
            $insert->bindValue(':forename', $user->forename);
            $insert->bindValue(':surname', $user->surname);
            $insert->execute();
            //$insert->execute(array(':id' => $user->id, ':forename' => $user->forename, ':surname' => $user->surname));
            //$insert->execute(array(':id' => "16", ':forename' => "Bill", ':surname' => "Gates"));
            echo $user->forename . " sucessfully added to database";

        } catch (Exception $e) {
            echo "Database insertion failed" . var_dump($e);
        };
}

?>

1 个答案:

答案 0 :(得分:2)

您的$ user变量未在dbinsert()范围内定义。您可以将dbinsert()函数添加到用户类中。或者将$ user设置为dbinsert()的参数。

   <?php
Require("dbconnect.php");

class Userclass{
    public $id;
    public $forename;
    public $surname;
    public $greeting = "Mr";

    public function dbinsert(){


        try {
            $sql = "INSERT INTO testtable (id, forename, surname)
                VALUES (:id, :forename, :surname)";    
            $insert = $db->prepare($sql);
            $insert->bindValue(':id', $this->id);
            $insert->bindValue(':forename', $this->forename);
            $insert->bindValue(':surname', $this->surname);
            $insert->execute();
            echo $this->forename . " sucessfully added to database";

        } catch (Exception $e) {
            echo "Database insertion failed" . var_dump($e);
        };
    }
};


try {
    $user = new Userclass;
    $user->id = $_POST["id"];
    $user->forename = $_POST["forename"];
    $user->surname = $_POST["surname"];
    $user->dbinsert();
} catch (Exception $e) {
    echo "failed";
    exit;
}

?>