我有一个查询,检查数据库中是否存在插入的名字和姓氏,我想检查名字和姓氏或电子邮件,所以如果插入的名字和姓氏存在,那么用户找到了,如果电子邮件只存在于数据库中,那么用户也会找到,该怎么做?
以下是代码:
$query = "SELECT * FROM users WHERE first_name='" . $f_name . "' AND last_name='" . $l_name . "'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(empty($row)){
//some code to add the user to the database
}else{
//user is found
}
所以我希望别的意思是数据库中不存在(名字和姓氏)或(仅电子邮件)
答案 0 :(得分:0)
$query = "SELECT * FROM users WHERE (first_name='" . $f_name . "' AND last_name='" . $l_name . "') OR (email = '" . $email . "')";
答案 1 :(得分:0)
希望这有帮助,
$query = "SELECT * FROM users WHERE (first_name='" . $f_name . "' AND
last_name='" . $l_name . "') OR (email = '" . $email . "')";
编辑 -
Barclick Flores Velasquez他的答案对我来说还没有加载,这也是正确的。
答案 2 :(得分:0)
只需要使用<?php
$query = "SELECT * FROM users WHERE (`first_name` = '".$f_name."' AND `last_name` = '".$l_name."') OR (`email_column_name` = '".$email."') ";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(empty($row)){
//some code to add the user to the database
} else {
//user is found
}?>
条件附加您的查询。
<?php
$mysqli = new mysqli("localhost", "user_name", "password", "db_name");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE (`first_name` = ? AND `last_name` = ?) OR (`email_column_name` = ?) ");
$stmt->bind_param("sss", $f_name, $l_name, $email);
$result = $stmt->execute();
if($result->num_rows > 0){
//user is found
} else {
//some code to add the user to the database
}?>
我建议你使用预准备语句来避免SQL注入
面向对象的风格
<?php
$mysqli = mysqli_connect("localhost", "user_name", "password", "db_name");
$stmt = mysqli_prepare($mysqli, "SELECT * FROM users WHERE (`first_name` = ? AND `last_name` = ?) OR (`email_column_name` = ?) ");
mysqli_stmt_bind_param($stmt, "sss", $f_name, $l_name, $email);
$result = mysqli_stmt_execute($stmt);
if(mysqli_num_rows($result) > 0){
//user is found
} else {
//some code to add the user to the database
}?>
程序风格
{{1}}
快速链接