ThingEngineer / PHP-MySQLi-Database-Class

Wrapper for a PHP MySQL class, which utilizes MySQLi and prepared statements.
Other
3.3k stars 1.34k forks source link

possible bug in onDuplicate() #955

Open OpNop opened 3 years ago

OpNop commented 3 years ago

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

JuneTwooo commented 2 years ago

It seem that this bug has not been fixed yet