skip to Main Content

enter image description hereI tried the below code to get the last inserted id so as to insert it to another table but somehow using $this->$conn->lastInsertId() doesn’t seem to work.

Anyone has any idea?

if (!( $stmt = $this->conn->prepare("INSERT INTO company(company_name,address_line1,address_line2,postal_code,country,contact_no,email,wifi_name,website_url,contact_person,parent_id,created_by,created_date,updated_date,deleted, wifi_name2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"))) {
        echo "Prepare failed: (" . $this->conn->errno . ")" . $this->conn->error;
    } else {
        if (!$stmt->bind_param('ssssssssssiissis', $name, $address_line1, $address_line2, $postal_code, $country, $phone, $email, $wifi, $url, $contact, $p_id, $staff_id, $today, $updated, $deleted, $wifi2)) {
            echo "Binding parameters failed: (" . $stmt->errno . ")" . $stmt->error;
        } else {
            if (!$stmt->execute()) {
                echo "Execute failed: (" . $stmt->errno . ")" . $stmt->error;
                return FALSE;
            } else {
                echo $this->$conn->lastInsertId();
                $stmt->close();
                return TRUE;
            }
        }
    }

2

Answers


  1. Chosen as BEST ANSWER

    For my case, which I believe I am not using the pdo accessing method, this works:

    $stmt->insert_id;
    

  2. The code seems to be correct.

    Maybe you don’t have the field ID AUTOIMCREMENT PRIMARY on that table.

    lastInsertId() can return the new ID only if the field is AUTOIMCREMENT PRIMARY.

    Try also do query this to see if you get the last inserted id:

    $stmt = $db->query("SELECT LAST_INSERT_ID()");
    $lastInsertId = $stmt->fetchColumn();
    

    If the aboves aren’t your case, you must analyze every single step to discover the issue:

    • run the script to see what it prints
    • see in the database if the new row was inserted and what it contains, particularly the id field
    • try yo make the insert directly in phpmyadmin and then execute `SELECT LAST_INSERT_ID()’ to see if the manually query works
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search