Search code examples
phpmysqlwechat

how to set default value as text and auto increment in mysql table


I am trying to set the default username as like wechat which have something like wxid_1234 so can we set default username in our mysql table?

There is a table named 'username' and have two columns: 'username' and 'phone'. Since 'username' needs to be set something like foo_123 and may be auto increased with foo_124, foo_125 etc. It could be changed afterwards.

So is it possible to set the username like that? if not what is the other method to do it.


Solution

  • Yes, you can do that, but it would be two queries, and you would have to have an autoincrementing user_id as another column:

    $sql = $dbo->prepare('INSERT INTO users(username, phone) values("temp", ?)');
    $sql->execute(array($phone_number));
    $id = $dbo->lastInsertId(); 
    $sql = $dbo->prepare("UPDATE users SET username=? WHERE id=?");
    $username = "foo_" . $id;
    $sql->execute(array($username, $id));