将最后一个id插入变量发送到php中的另一个页面

时间:2016-07-24 05:52:14

标签: php mysql pdo last-insert-id

在这段代码中我必须在DB中插入一些值,然后我必须在DB中插入最后一个id并将其发送到另一个页面以显示该id行的值。这是我在DB中插入数据的代码:

try {
    $con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";

    $con->exec($sql_basic);
    $last_id = $con->$lastInsertId();
} catch (PDOException $e) {
    echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
}

$con = null;

header('Location: DB-Read.php?id=' . $last_id);

在另一个php页面中,我必须使用$last_id并使用它。这是我的代码:

try {
    $user_id = $id;
    $conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
    $stmt->execute();
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    echo "this is username: " . $result;

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

$conn = null;

header('Location: show-edit.php?id=' . $last_id);

首先$lastInsertId()没有工作!! 在那之后,从第一页开始$last_id我的方式是真的吗?

2 个答案:

答案 0 :(得分:1)

lastInsertIdPDO对象的一种方法。您需要致电$conn->lastInsertId();

您给定的语法$conn->$lastInsertId();是有效的,但是,它没有做到,您期望的是什么。它认为$lastInsertId是一个包含要调用的方法名称的变量。以下示例也可以使用:

$method_name = 'lastInsertId';
$conn->$method_name();

请注意,您的解决方案可让任​​何人获取您表格的任何一行。考虑使用会话。

答案 1 :(得分:-1)

尝试这个: 使用会话

try {
    $con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $sql_basic = "INSERT INTO user_basic_info    (first_name,last_name,address,profile_pic,resume_file)
VALUES     ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";

   $con->exec($sql_basic);
   $_SESSION['id'] = $con->lastInsertId(); //it's a method
} catch (PDOException $e) {
    echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
$con = null;

header('Location: DB-Read.php?id=' . $last_id);

现在使用此代码

try {
    $user_id = $_SESSION['id'];
    $conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
    $stmt->execute();
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    echo "this is username: " . $result;

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

$conn = null;

header('Location: show-edit.php?id=' . $last_id);