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

时间:2013-04-30 15:57:57

标签: php mysql select insert

我想要做的就是在将数据库插入数据库后检索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

(我很欣赏我是一个完整的新手,并且对于使代码更好的任何指针都表示赞赏)

2 个答案:

答案 0 :(得分:1)

最后一个插入ID方法应该这样做: -

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

答案 1 :(得分:0)

假设contact_id是您的主键,您可以使用PDO :: lastInsertId(),所以在您的情况下:

$cid = $conn->lastInsertId();