如何从另一个方法php中的方法返回一个值

时间:2014-01-07 17:03:08

标签: php pdo

我有两个方法。一个方法是插入数据,另一个方法是获取插入数据的id。我尝试了几个测试,但它没有给出任何返回值。是否可以从另一个方法传递返回值?

public function insertRegistrantInfo($fname, $lname) {


    $query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");

    $query->bindValue(1, $fname);
    $query->bindValue(2, $lname);


    try {

        $row = $query->execute();
        //$log = $this->getSessionID($email);       
        return $this->getSessionID($email);     

        #mail function can be added here

        }catch(PDOException $e) {

        die($e->getMessage());

    }
}

public function getSessionID($email) {
    try {
    //global $bcrypt;

    $query = $this->db->prepare("SELECT `id` FROM `registrants_info` WHERE `email` = ?");

    $query->bindValue(1, $email);



        $query->execute();
        $data1 = $query->fetch();

        $id  = $data1['id'];
        //echo $id;
        return $id;

    } catch(PDOException $e) {
        die($e->getMessage());
        }
}

,返回的页面在这里:

if($data = $admin->insertRegistrantInfo($fname, $lname) == true) {
    session_regenerate_id(true);
    $_SESSION['id'] =  $data;

            //print_r($_SESSION);
    header('location: registry.php');
    exit();

}

1 个答案:

答案 0 :(得分:1)

在查询对象上使用lastInsertID()方法而不是第二个查询

public function insertRegistrantInfo($fname, $lname) {


$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");

$query->bindValue(1, $fname);
$query->bindValue(2, $lname);


try {

    $row = $query->execute();
    $insertId = $query->lastInsertId(); // <!-- Use this instead of a second query     

    #mail function can be added here

    }catch(PDOException $e) {

    die($e->getMessage());

}

}

同样重要的是要注意,您没有在数据库中插入“电子邮件地址”,因此如果要使用其他SELECT语句,查询无法通过该字段找到它。您可能想要完成INSERT语句。

相关问题