在这段代码中,我必须在DB中插入一些值,然后我必须获取插入DB中的最后一个id,并将其发送到另一个页面以显示该id行的值。这是我在数据库中插入数据的代码:
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
吗?
lastInsertId
是PDO
对象的一个方法。您需要致电$conn->lastInsertId();
。
您给定的语法$conn->$lastInsertId();
是有效的,但它并不能满足您的期望。它认为$lastInsertId
是一个包含要调用的方法名称的变量。以下示例也适用:
$method_name = 'lastInsertId';
$conn->$method_name();
请注意,您的解决方案使任何人都可以获取表中的任何一行。考虑使用会话
试试这个: 使用会话:
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);