gpt4 book ai didi

php - 如何在 PHP 中插入后从 MYSQL 表中检索 ID

转载 作者:行者123 更新时间:2023-11-29 03:05:25 24 4
gpt4 key购买 nike

我要做的就是在向数据库中插入一行后检索 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 的方法应该这样做:-

http://php.net/manual/en/pdo.lastinsertid.php

关于php - 如何在 PHP 中插入后从 MYSQL 表中检索 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com