繁体   English   中英

通过PHP的MySQL搜索方法

[英]MySQL search method through PHP

关于用php搜索mysql数据库的方法的快速提问。

现在,我有一个应该搜索并返回结果的函数。 假设我有两个数据库,一个数据库是User,一个数据库是Profile。 用户存储用户名,电子邮件,密码。 个人资料存储用户的名字,姓氏,地址,生日。 现在,我不确定该怎么做,但这是我到目前为止所掌握的。

我希望能够搜索两个表并通过覆盖的表返回结果列表,但是我不知道如何降低复杂性。 该函数将包含NULL或变量的值。 现在,这是我的草图:

if(!empty($username)):
$append .= "WHERE";
$append .= "username = ".$username."";
endif;
if(!empty($email)):
$append .= "WHERE";
$append2 .= "email= ".$email."";
endif;
if(!empty($firstname)):
$append .= "WHERE";
$append2 .= "firstname = ".$firstname."";
endif;
if(!empty($lastname)):
$append .= "WHERE";
$append2 .= "lastname= ".$lastname."";
endif;

$sql = "select * FROM Users ".$append."";
$result = mysql_query($sql);
$sql2 = "select * FROM Profile ".$append2."";
$result2 = mysql_query($sql2);
$userId = mysql_fetch_row($result2);
$userId['id'] = $id; <-- this is the one I will call to display data.

如何有效地执行此操作并搜索/返回所有唯一/不同的用户ID? 两个表都包含用户ID /递增ID号(用户表为User_ID,配置文件表为acct_id)。 我知道这段代码有点错误...不用担心转义-我;已经整理好了。 我应该使用JOIN语句吗?

我面临的另一个问题是在WHERE和AND之间进行更改,因为有时如果设置了一个var但未设置另一个var,则我们必须使用AND而不是仅使用一个WHERE。 任何想法如何解决这个问题?

感谢您的输入!

对于您的WHERE子句,最好是使用数组,然后像这样进行implode()

$and_where = array();
if (!empty($username))
    $and_where[] = "username = ".$username;
if (!empty($email))
    $and_where[] = "email = ".$email;
//etc
if (count($and_where) > 0)
    $where = " WHERE ".implode(" AND ", $and_where);
else
    $where = "";

这两个表在某种程度上相关吗? 如果acct_idacct_id的外键, User_id可以使用INNER JOIN$where如上所示)

$query = "SELECT Users.col, ..., Profile.col, ... FROM Users
    INNER JOIN Profile ON Users.user_id = Profile.acct_id".$where;

如果不是,您可以简单地将它们UNION

$users_and_where = array();
$profiles_and_where = array();
if (!empty($username))
    $users_and_where[] = "username = ".$username;
if (!empty($email))
    $users_and_where[] = "email = ".$email;
//etc
if (!empty($firstname))
    $profiles_and_where[] = "firstname = ".$firstname;
if (!empty($lastname))
    $profiles_and_where[] = "lastname = ".$lastname;
//etc
if (count($users_and_where) > 0)
    $users_where = " WHERE ".implode(" AND ", $users_and_where);
else
    $users_where = "";
if (count($profiles_and_where) > 0)
    $profiles_where = " WHERE ".implode(" AND ", $users_and_where);
else
    $profiles_where = "";
$query = "(SELECT col1, col2, ... FROM Users".$users_where.")
    UNION
        (SELECT col1, col2, ... FROM Profile".$profiles_where.")";

您应该尝试避免在查询中使用*并专门选择行,这样,当引入其他未在此处使用代码的列时,以后就不会有太多开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM