是否有人能够根据同一个表的另一个值来查找表的列值,从而为我提供MySQL关系查询?
例如,我有一个包含4列(id,name,email,password)的表。如何根据“email”列中的电子邮件查找某个用户的“id”列的值,并将结果(id)存储在变量中?
这是session()控制器功能
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['authorid'] = $author;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['authorid']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect.';
return FALSE;
}
}
我试过
SELECT id FROM article WHERE email='$email'
有更有效的方法吗?我也不完全确定如何在$author
会话变量中存储查询结果。
提前致谢。
答案 0 :(得分:1)
您的查询是完美的(条件是您正在清理$email
变量 - 请参阅Little Bobby Tables的故事。)
SELECT id FROM article WHERE email='$email'
要执行该查询并将变量$author
设置为返回值,只需:
$author = 0;
if( ( $idFromEmail = @mysql_query( "SELECT id FROM article WHERE email='".mysql_real_escape_string( $email )."'" ) )
&& mysql_num_rows( $idFromEmail )==1
&& ( $r = mysql_fetch_assoc( $idFromEmail ) ) ){
$author = $r['id'];
}
如果以上内容过于复杂而无法以长篇形式重写:
$author = 0;
if( !( $idFromEmail = @mysql_query( "SELECT id FROM article WHERE email='".mysql_real_escape_string( $email )."'" ) ){
// SQL Query Failed
}elseif( mysql_num_rows( $idFromEmail )!=1 ){
// More than, or less than, one row returned
}else{
$r = mysql_fetch_assoc( $idFromEmail );
$author = $r['id'];
}