[英]PHP MYSQL. How to retrieve the same data from a table based on 2 different ID's in another table
[英]How to retrieve ID from MYSQL table after Insert in PHP
我要做的就是在數據庫中插入一行后檢索contact_id
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// Prepare Form Contents
// Split full name to First and Last Name
$both = $_POST['contact_name']; // Get the full name
$both = str_replace('.', '. ', $both); // Give it a new variable name
$both = preg_replace('/[^ ]+\./', '', $both); // Strip Spaces
$both = trim(str_replace(' ', ' ', $both));
list($fname, $lname) = explode(" ", $both, 2); // Get the two variables
// Set values for contact
$email = $_POST['contact_email'];
$tel = $_POST['contact_tel'];
$jtitle = $_POST['contact_jtitle'];
// Get the Date
$today = date("Y-m-d");
// Define an insert query
$sql = "INSERT INTO `contacts` (`first_name`, `last_name`, `email`, `telephone`, `job_title`, `reg_date`)
VALUES
('$fname','$lname','$email','$tel','$jtitle','$today')";
$count = $conn->exec($sql);
// Get the Contact ID
$foo = "SELECT `contact_id` FROM `contacts` WHERE `email` = ' .$email. '";
$cid = $conn->exec($foo);
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
問題是$ cid總是返回0
(我很感激我是一個完整的新手,對於使代碼總體上變得更好的任何指針,我們都表示贊賞)
最后插入id方法應該做到這一點:
假設contact_id是您的主鍵,則可以使用PDO :: lastInsertId(),因此在您的情況下:
$cid = $conn->lastInsertId();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.