catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.83k stars 1.15k forks source link

insert return a array or string? #324

Closed iyaozhen closed 7 years ago

iyaozhen commented 8 years ago

insert($table, $data) Return: [number] The last insert id

But in code: https://github.com/catfan/Medoo/blob/634bcef389e4eaa40d10e6d66a9eecc0f7638cc7/medoo.php#L717

$lastId = array();
……
$lastId[] = $this->pdo->lastInsertId();
……
return count($lastId) > 1 ? $lastId : $lastId[ 0 ];

It is better?

if (count($lastId) === 0) {
    return 0;
}
else {
    return count($lastId) > 1 ? (int)end($lastId) : (int)$lastId[0];
}
SyuTingSong commented 8 years ago

When the $data argument includes multi rows, an array contains each inserted row id will be returned. end($lastId) gets the last element of the array and it is incorrect.

The numeric string comes from the return value of PDO::lastInsertId(). Type-casting by force may lose precision if the underlying database use very large int as auto-increment id.

iyaozhen commented 8 years ago

@SyuTingSong Thx, you are right.

I think should modify Documentation (http://medoo.in/api/insert). "Return: [string|array] The last insert id"

And in php documentation:

PDO::lastInsertId Note: This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

Medoo Documentation would be best warn this.

zozowind commented 8 years ago

when using enter mssql with freetds, PDO::lastInsertId() [pdo.lastinsertid]: SQLSTATE[IM001]: Driver does not support this function: driver does not support lastInsertId() I add a try-catch

try {
    $lastId[] = $this->pdo->lastInsertId();
}catch (Exception $e){
    return 0;
}
catfan commented 7 years ago

It's updated on Medoo 1.2. Use new API id() instead.