使用以下代码,如何在数据库中添加默认值“ user”和“ id”字段的用户名,例如对于第15个用户,该用户名变为“ user15”?
我不确定要在何处添加默认用户名,语法也不是100%。
说明:我想要一个静态字符串(“用户”),并将其与数据库中自动递增的“ id”字段连接起来。
更新:似乎不可能立即连接自动递增的值,因此:关于如何生成默认用户名的任何建议?用户名字段为UNIQUE。
for attribute in resp[0]['attributes']:
if attribute['name'] == 'buttonState' and attribute['value']['data'] is False:
# Do your thing here
答案 0 :(得分:1)
我在评论中提出了这个建议,但让我尝试一个答案以使其更加充实。基本上,想法是插入新记录,然后获取插入ID,然后更新有问题的记录。
if (something_supposed_to_happen_here()) {
$firstname = $profile['first_name'];
$lastname = $profile['last_name'];
$email = $profile['email'];
$picture = $profile['picture']['url'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("
INSERT INTO users (
firstname,
lastname,
email,
picture,
token
)
VALUES (
:firstname,
:lastname,
:email,
:picture,
:token)"
);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':picture', $picture);
$stmt->bindParam(':token', $accessToken);
$stmt->execute();
// Suggestion follows
$insertId = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE users SET username = :username WHERE id = :id');
$userId = 'user' . $insertId;
$stmt->bindParam(':username', $userId);
$stmt->bindParam(':id', $insertId);
$stmt->execute();
// End suggestion
echo "Thank you for registering";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
} else {
$loginUrl = $helper->getLoginUrl('mywebsite.com/fblogin/index.php', $permissions);
echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
}
请注意,这假设您的自动递增ID字段称为id
,而用户名字段称为username
。
答案 1 :(得分:0)
仅通过与Facebook的用户ID串联即可解决:
$firstname = $profile['first_name'];
$lastname = $profile['last_name'];
$email = $profile['email'];
$picture = $profile['picture']['url'];
$userstatus = "1";
$fbuserid = $profile['id'];
$defaultUsername = 'user_' . $fbuserid; // This line solved it.
//<editor-fold desc="> Insert the data above this into the database">
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO users (firstname, lastname, email, picture, status, token, oauth_uid)
VALUES (:firstname, :lastname, :email, :picture, :userstatus, :token, :oauth_uid)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':picture', $picture);
$stmt->bindParam(':userstatus', $userstatus);
$stmt->bindParam(':token', $fbuserid); // just oauth_uid stored in a better named column, also storing that with the line below
$stmt->bindParam(':oauth_uid', $fbuserid); // this is the original of this and the one above