0

I'm trying to make a contract which will check if there is already some data in mapping. If so, it will then replace the old data with the new. If not - insert new record. Sounds easy, but im learning and spent hours triyng to find a solution. How can I do that?

function MyToken() public
{

}

struct DATA
{
    uint Id;
    uint Date;
}

mapping (uint => DATA) public data;
uint public total = 0;

function add(uint Id, uint Date) public returns (uint)
{
    if(data[Id].Id == 0) // Checking if there is some records with this ID
    {
        data[total] = DATA(Id, Date);
        total++;
        return total;
    }
    else // If some data found - replace it with new
    {
        data[Id].Date = Date;
    }
}

For some reason this code just insert new records. I need to have it changing old data.

0

2 Answers 2

0

I don't think you need s struct for the above code. If you are saving Id and date only then you can do that without a struct. Just use Id as a key and date as the value.

mapping (uint => uint) public data;

function add(uint Id, uint Date) public returns (uint)
{
if(data[Id] == 0) // Checking if there is a date with this ID
{
    data[total] = Date;
    total++;
    return total;
}
else // If some date found - replace it with new
{
    data[Id] = Date;
}
}
0

You are checking for the existence of Id and later add a new to total.

if(data[Id].Id == 0) // Checking if there is some records with this ID
{
     data[total] = DATA(Id, Date);

It appears you want to create a new record for Id instead.

 data[Id] = DATA(Id, Date);

Not the answer you're looking for? Browse other questions tagged or ask your own question.