PDO返回班级

时间:2018-02-01 13:19:01

标签: php class object pdo

我对如何使用PDO使用返回最后一个ID感到困惑。我找到的所有教程/答案都是基于它没有在课堂上如此努力寻找答案。

我得到的代码如下。这一切都与返回最后一个id有关。返回true时,它将插入数据库并重定向到另一个页面。我正确使用了返回ID吗?如果是这样,我如何回显用户重定向到的页面上的ID?

编辑:谢谢你的答案 - 我更新了代码,用return last id部分替换'true'。但是,我仍然在努力返回ID,在下面添加了新代码。数据库插入工作正常,我只是在努力输出返回的内容。

谢谢,

数据库查询:

public function insertNewCustomer($data){
    $this->db->query("INSERT INTO Customers (First_Name, Surname, Email) VALUES (:firstname, :surname, :email)");
    //Bind Data
    $this->db->bind(':firstname', $data['firstname']);
    $this->db->bind(':surname', $data['surname']);
    $this->db->bind(':email', $data['email']);


    //Execute
    if($this->db->execute()){
        return true;
    } else {
        return false;
    }

    //Get ID of new customer
    $lastID = $this->db->lastInsertId();



}

我如何回应ID:

$itinerary = new Itinerary;

$template->ID = $itinerary->insertNewCustomer();

echo $ID->lastID;

尝试回显ID的新代码:

if(isset($_GET['firstname'])){

$data = array();
$data['firstname'] = $_GET['firstname']; 
$data['surname'] = $_GET['surname']; 
$data['email'] = $_GET['email']; 

if($itinerary->insertNewCustomer($data)){

echo $itinerary->insertNewCustomer();


} else { echo 'did not work';}

2 个答案:

答案 0 :(得分:2)

问题是因为您在运行db->lastInsertId();

之前返回

改变这个:

//Execute
if($this->db->execute()){
    return true;
} else {
    return false;
}   

//Get ID of new customer
$lastID = $this->db->lastInsertId();

致:

//Execute
if($this->db->execute()){
    return $this->db->lastInsertId();
} else {
    return false;
}

$itinerary->insertNewCustomer();现在将在失败的执行或插入ID上返回false。

答案 1 :(得分:0)

<?php
// Use this function

    public function insertNewCustomer($data){
        $this->db->query("INSERT INTO Customers (First_Name, Surname, Email) VALUES (:firstname, :surname, :email)");
        //Bind Data
        $this->db->bind(':firstname', $data['firstname']);
        $this->db->bind(':surname', $data['surname']);
        $this->db->bind(':email', $data['email']);


        //Execute
        if($this->db->execute()){
        //Get ID of new customer
            return $this->db->lastInsertId();
        } 
        return false;
    }

//超出功能范围     $ itinerary =新行程;

$template->ID = $itinerary->insertNewCustomer(); // Call to function

if($template->ID!==false){echo "Customer ID". $template->ID;}
else{
echo "Customer insertion failed";
}
相关问题