简体   繁体   中英

PDO not being able to return the last_insert_id

   <?php
    session_start();


            $userid = $_SESSION['userid'];
            $categorynumber=0;
            $categorynumber = create_category($userid);
            //keep the category number for future reference
            if($categorynumber > 0){
                $_SESSION['categorynumber'] = $categorynumber;
            }

            echo $categorynumber;



    ?>

echo $categorynumber prints 0

    function create_category($userid)
{

    // connect to database with PDO
    $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE;
    $dbh = new PDO($dsn, DB_USER, DB_PASSWORD);

    // insert category and get the category_id
    $categorynumber = 0;
    $stmt = $dbh->prepare("INSERT INTO categories (userid, name) VALUES (:userid, :name);SELECT LAST_INSERT_ID();");
    $stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
    $stmt->bindValue(':name', 'test7', PDO::PARAM_STR);
    if ($stmt->execute())
    {
        $result = array();
        while ($row = $stmt->fetch()) {
            array_push($result, $row);
        }

        if (isset($result[0][0]))
        $categorynumber = $result[0][0];

    }   

    // close database and return null 
    $dbh = null;
    return $categorynumber;
}

What am I doing wrong here, so that I cannot retrieve the last id of the created entry? How can I return the last_insert_id(); and assign it to the $_SESSION['categorynumber']??

I have managed to achieve what I wanted with the following line:

$categorynumber = $dbh->lastInsertId();

full example:

    function create_category($userid)
{

    // connect to database with PDO
    $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE;
    $dbh = new PDO($dsn, DB_USER, DB_PASSWORD);

    // insert category and get the category_id
    $categorynumber = 0;
    $stmt = $dbh->prepare("INSERT INTO categories (userid, name) VALUES (:userid, :name);");
    $stmt->bindValue(':userid', $userid, PDO::PARAM_STR);
    $stmt->bindValue(':name', 'test7', PDO::PARAM_STR);
    $stmt->execute();
    $categorynumber = $dbh->lastInsertId();

    // close database and return null 
    $dbh = null;
    return $categorynumber;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM