簡體   English   中英

在PHP中插入后如何從MYSQL表中檢索ID

[英]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方法應該做到這一點:

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

假設contact_id是您的主鍵,則可以使用PDO :: lastInsertId(),因此在您的情況下:

$cid = $conn->lastInsertId();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM