Retrieving the last insert id from MySql using PHP

前端 未结 7 1083
时光说笑
时光说笑 2020-12-22 08:38

I have two tables in MySql database, one is sales_order and the other is sales_order_details which contains the details of the order in the s

7条回答
  •  失恋的感觉
    2020-12-22 09:42

     1. Database
    
        CREATE TABLE MyGuests (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        email VARCHAR(50),
        reg_date TIMESTAMP
        )
    
    
    -------------------------------------------------------------------
      1.   Example (MySQLi Object-oriented)
    
    -------------------------------------------------------------------
        connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
    
        $sql = "INSERT INTO MyGuests (firstname, lastname, email)
        VALUES ('John', 'Doe', 'john@example.com')";
    
        if ($conn->query($sql) === TRUE) {
            $last_id = $conn->insert_id;
            echo "New record created successfully. Last inserted ID is: " . $last_id;
        } else {
            echo "Error: " . $sql . "
    " . $conn->error; } $conn->close(); ?> ------------------------------------------------------------------- 2. Example (MySQLi Procedural) ------------------------------------------------------------------- " . mysqli_error($conn); } mysqli_close($conn); ?> ------------------------------------------------------------------- 3. Example (PDO) ------------------------------------------------------------------- setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; // use exec() because no results are returned $conn->exec($sql); $last_id = $conn->lastInsertId(); echo "New record created successfully. Last inserted ID is: " . $last_id; } catch(PDOException $e) { echo $sql . "
    " . $e->getMessage(); } $conn = null; ?>

提交回复
热议问题