我已经尝试了几个小时来获得一个解决方案来检查用户名是否存在,但它会不断添加我添加的相同用户名(不输出它存在的错误)。
我目前的职能;
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
function name_exists($name){
$con = mysqli_connect('localhost','root','','database');
$name = ($name);
$query = mysqli_query($con,"SELECT COUNT(id) FROM users WHERE name = '$name'");
// Count the amount of rows where username = $unsername
$check = mysqli_num_rows($query);
return (mysqli_result($query, 0) == 1) ? true:false;
}
我验证用户名和其他内容的完整代码如下所示;
//Validates Username
if(empty($error)) {
if(name_exists($name)==true){
$email_error = "Sorry, the username: $name is already Taken.";
$error = true;
}
if(empty($name)) {
$error = true;
$email_error = "You Forgot to Enter Your Username!";
}
if(!preg_match('/^\w{5,}$/', $name)){
$error = true;
$email_error= "Invalid Username format.";
// valid username, alphanumeric & longer than or equals 5 chars
}
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error)
{
// prepare and bind
$stmt = $con->prepare("INSERT INTO users (name,email,password) VALUES (?, ?, md5(?))");
$stmt->bind_param("sss", $name, $email, $password);
//$stmt->execute();
if( $stmt->execute() == true) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
数据库结构
id(int8)
name(varchar 30)
email(varchar60)
password(varchar40)
答案 0 :(得分:0)
首先,您可以向数据库中的name列添加唯一标识符,以避免重复插入。
其次让查询为
SELECT COUNT(id)
FROM users
WHERE name = ' ".$name." ' ";
在单引号内,变量$name
被视为字符串$name
,而不是被替换为$name
答案 1 :(得分:0)
取代:
page = Page.query.filter_by(id=value).one()
使用:
for id in tag_ids:
tag = Tag.query.filter_by(id=id).one() #wanna avoid this
page.tags.append(tag)
我测试过,它对我有用