2013-04-30 29 views
2

所有我試圖做的是插入一行到數據庫如何在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

(我明白我是一個完整的新手,並使得代碼更一般的指針表示讚賞)

+1

你容易受到[SQL注入攻擊(HTTP://鮑比-tables.com)。在解決任何其他代碼問題之前,請先了解並解決問題。然後RTLM:http://php.net/manual/en/pdo.exec.php你正在使用' - > exec()'不正確。無論如何,你的選擇有語法錯誤,所以無論你如何執行,它都會失敗。 – 2013-04-30 15:59:51

+0

如果'contact_id'列是主鍵,那麼檢查最後插入的id(使用PDO)而不是使用select語句來確定id。同時檢查使用PDO的示例。你會從中學到很多東西。 – bestprogrammerintheworld 2013-04-30 18:47:51

回答

0

假設CONTACT_ID是你的主鍵,你可以使用PDO :: lastInsertId(),所以你的情況:

$cid = $conn->lastInsertId(); 
相關問題