【问题标题】:How to retrieve ID from MYSQL table after Insert in PHP如何在 PHP 中插入后从 MYSQL 表中检索 ID
【发布时间】:2013-04-24 14:58:11
【问题描述】:

我要做的就是在向数据库中插入一行后检索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

(感谢我是一个完全的新手,任何使代码变得更好的指针都值得赞赏)

【问题讨论】:

  • 您容易受到SQL injection attacks 的攻击。在处理代码的任何其他问题之前,了解这一点并解决问题。然后 RTLM:php.net/manual/en/pdo.exec.php 你错误地使用了->exec()。而且您的选择无论如何都有语法错误,因此无论您如何执行它都会失败。
  • 如果 'contact_id' 列是主键,则检查最后插入的 id(使用 PDO)而不是使用 select-statement 来确定 id。还要检查使用 PDO 的示例。你会从中学到很多东西。

标签: php mysql select insert


【解决方案1】:

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

$cid = $conn->lastInsertId();

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 2015-06-02
      • 2011-09-08
      • 2018-06-08
      相关资源
      最近更新 更多