如何在PHP中插入后检索MySQL表ID
问题描述:
所有我试图做的是插入一行到数据库如何在PHP中插入后检索MySQL表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();
}
问题后取回CONTACT_ID是$ CID总是返回0
(我明白我是一个完整的新手,并使得代码更一般的指针表示赞赏)
答
假设CONTACT_ID是你的主键,你可以使用PDO :: lastInsertId(),所以你的情况:
$cid = $conn->lastInsertId();
你容易受到[SQL注入攻击(HTTP://鲍比-tables.com)。在解决任何其他代码问题之前,请先了解并解决问题。然后RTLM:http://php.net/manual/en/pdo.exec.php你正在使用' - > exec()'不正确。无论如何,你的选择有语法错误,所以无论你如何执行,它都会失败。 – 2013-04-30 15:59:51
如果'contact_id'列是主键,那么检查最后插入的id(使用PDO)而不是使用select语句来确定id。同时检查使用PDO的示例。你会从中学到很多东西。 – bestprogrammerintheworld 2013-04-30 18:47:51