如何将变量传递给另一个页面中的类

时间:2016-09-03 13:39:40

标签: php pdo

我正在尝试将数据插入到我的数据库中。我有三个页面。首先是 index.php 我在哪里。第二个是 db.php 保持与数据库的连接。第三个是 insert.php ,它包含插入代码。我面临的问题是,当我进行插入 < , 数据库 类的em> child ,它工作正常,但当我使用插入类时,一个单独的类来自< strong>数据库 class.It给了我一个错误。简而言之,我无法将包含数据库连接 OBJECT 的变量传递给 insert 类。

的index.php

<?php

function __autoload($cl){

    require_once "classes_lib/$cl.php";

}

$database = new db();
if(isset($_POST['submit']))
{
     $name = $_POST['name'];
     $email = $_POST['email'];
     $ph = $_POST['phone'];

    try
    {
        $ins = new insert($database);
        echo $ins->insertUser($name, $email, $ph);

    }
    catch(PDOEXCEPTION $e)
    {
        echo $this->con_error . $e->getmessage();
    }
}

classes_lib / db.php中

<?php

class db{

    public $con;
    public $con_error;

    public function connect(){

        try
        {
            $this->con = new PDO("mysql:host=localhost;dbname=oop","root","");
        }

        catch(PDOException $e)
        {
            echo $this->con_error = "An error in connecting to database" . $e->getmessage();
        }

    }

    public function __construct(){

        return $this->connect();

    }

}

classes_lib / insert.php

<?php

class insert{

    public $dbs;

    public function __construct($database){

        $this->dbs =  $database;
        return $this->dbs;

    }

    public function insertUser($name,$email,$ph){

        $stmt = $this->con->prepare("INSERT INTO `users` (`name`,`email`,`phone`) VALUES (:name,:email,:phone)");

        $stmt->bindParam(":name",$name);
        $stmt->bindParam(":email",$email);
        $stmt->bindParam(":phone",$ph);

        $stmt->execute();

    }

}

我对错误感到厌倦。任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

为什么不像这样构建代码: 在index.php中:include / require插入类然后

if (isset($_POST['submit'])) { 
    //..call the insert class and pass the $_POST params in the insertUser    method 
    $class_insert = new insert();
    $class_insert->insertUser($_POST); // pass the values to the method
}

然后在你的类insert中,require_once db.php然后扩展它:

class insert extends db
{
    // ..blah blah...

    public function insertUser($data){  // $data = $_POST param
        $database = new db();
        $db = $database->connect();
        $sql = "INSERT INTO users (name, email, phone) VALUES (:name, :email, :phone)";
        $q= $db->prepare($sql);

        $q->bindValue(':name',$data['name']);
        $q->bindValue(':email',$data['email']);
        $q->bindValue(':phone',$data['phone']);

        $q->execute();

    }
}        
相关问题