0

I use solidity to store users information so before that i want to check if the user id already exist or no, Can any one help me with this code ?

i see some solution using array or require all parameters of structure and i don't prefer that, can i do this without these choices?

this function to store user information, if any one have a better code for that, i will appreciate it.

contract Contract {

    struct User{
    string fname;
    string Email;
    uint256 age;
    }


    mapping(uint => User)public users; 


 function addDoctor(uint _id, string memory fname, string memory Email,
    uint256 age) public {


         users[_id] = User(fname,email,age);

     }
 }

thanks in advanced.

1 Answer 1

0

You probably want to add bool valid or something similar in struct User, otherwise you'll need to use an implicit assumption in order to check whether or not a use exists (for example, age > 0).

UPDATE

Just to be clear, if you want to avoid handling an already-existing user, then you'll need to add:

require(!users[_id].valid);
users[_id].valid = true;

At the beginning of the function.

3
  • thanks a lot, Can i do that if i want to make a function return bool value ? because i want to use it outside the remix.
    – norah
    Commented May 14, 2020 at 15:33
  • @norah: Since variable users is declared public, you have at your disposal (implicitly generated by the compiler) function users(uint key) returns (yourStructFields). So if you add a bool field to your structure, then you'll be able to get it from Remix by calling that function. Commented May 14, 2020 at 16:07
  • I use these two functions and it work perfect: 'function isExist(uint _id) public view returns(bool){ return users[_id].valid;} function addUser(uint _id, string memory _fname, string memory _email, uint256 _age) public returns(bool) { bool q=isExist(_id); if(q==false){ users[_id] = user(_fname,email,_age,true);}}' thanks a lot.
    – norah
    Commented May 18, 2020 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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