PHP-MySQLi-Database-Class icon indicating copy to clipboard operation
PHP-MySQLi-Database-Class copied to clipboard

possible bug in onDuplicate()

Open OpNop opened this issue 4 years ago • 1 comments

It seems there is a bug in the onDuplicate() where, if the record exists the ID returned is always 1

Current code

$data = [
    'account' => $member->name,
];
$this->db->onDuplicate(['account'], 'id');
$id = $this->db->insert('members', $data);

if (!$id) {
    return $this->db->getLastError();
}

$member_guild = [
    'account_id' => $id,
    'guild_id' => $guild_id,
    'guild_rank' => $member->rank,
    'date_joined' => $this->db->func('STR_TO_DATE(?, ?)', [$member->joined, '%Y-%m-%dT%H:%i:%s.000Z']),
];

$mgid = $this->db->insert('members_guild', $member_guild);

This causes the records added to members_guild to have account_id be set to 1 if they was already a record in the members table

my current working solution is to call $id = $this->db->rawQueryValue("SELECT LAST_INSERT_ID() limit 1"); after the insert to get the last ID like so

```php
$data = [
    'account' => $member->name,
];
$this->db->onDuplicate(['account'], 'id');
$this->db->insert('members', $data);
$id = $this->db->rawQueryValue("SELECT LAST_INSERT_ID() limit 1")

if (!$id) {
    return $this->db->getLastError();
}

$member_guild = [
    'account_id' => $id,
    'guild_id' => $guild_id,
    'guild_rank' => $member->rank,
    'date_joined' => $this->db->func('STR_TO_DATE(?, ?)', [$member->joined, '%Y-%m-%dT%H:%i:%s.000Z']),
];

$mgid = $this->db->insert('members_guild', $member_guild);

I have not messed with debugging to much but I think the line at https://github.com/ThingEngineer/PHP-MySQLi-Database-Class/blob/master/MysqliDb.php#L1551 might be causing the issue, returning true if affected_rows is less then 1 but I could be wrong.

Using version 2.9.3

Thanks

OpNop avatar Feb 18 '21 03:02 OpNop

It seem that this bug has not been fixed yet

JuneTwooo avatar Nov 12 '21 13:11 JuneTwooo