对于我的注册系统,当用户注册时,我想确保不使用他们的用户名,电子邮件等。我有代码来检查用户名是否存在,我可能会对其他东西做同样的事情。
如何在不多次重写块的情况下执行此操作?
tl; dr:如何以紧凑的方式检查数据库中的更多内容?
$userquery = "SELECT * FROM users WHERE username = '$username'";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
die ("Username Already Exists.");
}
}
答案 0 :(得分:0)
在where子句中使用“OR”条件
$userquery = "SELECT * FROM users WHERE username = '$username' OR email= '$email'";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
die ("Username/Email Already Exists.");
}
}
修改
好的,
function doesitexist($mysqli,$table,$field,$value) {
$userquery = "SELECT * FROM $table WHERE $field = '$value' LIMIT 1";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} else {
return('Error running Query');
}
}
另一个编辑只是为了好玩。这应该采用一系列字段和值来检查一次调用。
$check = doesitexist($mysqli,'users',array('username'=>'bob','email'=>'someone@example.com'));
function doesitexist($mysqli,$table,$tocheck = array()) {
if (count($tocheck)>0) {
$where = '';
foreach ($tocheck as $field=>$value) {
$where .= $field." = '".addslashes($value)."' OR ";
}
$where = trim($where," OR ");
$userquery = "SELECT * FROM $table WHERE $where LIMIT 1";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} else {
return('Error running Query');
}
} else {
return("No Fields/Values to check");
}
}