我想只显示两个关系表中的一个帐户。例如,如果我查询我的帐号并输入帐号,则不会显示每个会员的帐户详细信息。所以在我的输出中,整个成员及其在数据库中的详细信息显示出来。如何才能设法只显示两个关系表中的一个帐户?我知道我的sql有问题。
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT member.*, account.*
FROM member, account
WHERE member.mem_id = account.mem_id';
mysql_select_db('databasename');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Account Number:{$row['Account_Number']} <br> ".
"First Name: {$row['fname']} <br> ".
"Last Name: {$row['lname']} <br> ".
"Address: {$row['address']} <br> ".
"Contact: {$row['contact']} <br> ".
"Share Capital: {$row['Share_Capital']} <br> ".
"Regular Savings: {$row['Regular_Savings']} <br> ".
"Power Savings: {$row['Power_Savings']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
现在这是输出。
Account Number:
First Name:
Last Name:
Address:
Contact:
Share Capital:
Regular Savings:
Power Savings:
答案 0 :(得分:1)
如果你没有选择任何人的答案是正确的,我怀疑你手头有数据问题。但假设您的记录真的是1对1,那么这肯定会这样做:
请注意,我在顶部添加了$ find_id作为参数
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$find_id = 12;
try
{
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if( !$conn )
throw new Exception( "Couldn't establish a connection" );
if( !mysql_select_db('databasename', $conn ) )
throw new Exception( "Database couldn't be selected" );
$sql = 'SELECT M.*, A.* FROM member M LEFT JOIN account A ON M.mem_id = A.mem_id
WHERE M.mem_id = $find_id';
if( !($retval = mysql_query( $sql, $conn )) )
throw new Exception( "No matching result, or query was borked; " . mysql_error() );
if( !($row = mysql_fetch_assoc( $retval )) )
throw new Exception( "No rows found, move along." );
print_r( $row );
}
catch( Exception $x )
{
echo "An exception occurred: " . $x->getMessage();
}
这就是丑陋的一切,但有几点需要注意:
可能不想使用mysql_ *函数;使用PDO(它不会出门) - 并使用准备好的参数来缓解SQL注入攻击。我可以添加的超级讨厌的小问题是,将用户表例程中的认证表例程与用户表例程分开通常是很好的逻辑,因为用户表通常最终被用于“外部”。查询auth以建立ID,然后在单独的线程中使用user表。这样,您的身份验证查询不会占用两个表。
祝你好运! 希望这会有所帮助。答案 1 :(得分:0)
要仅返回1个帐户,请尝试
'SELECT member.*, account.*
FROM member inner join account
on member.mem_id = account.mem_id limit 1';
但是,要检索memberid的成员和帐户,查询将需要更改为在mem_id上包含where谓词。例如:
$member_id = 'some memberid'
'SELECT member.*, account.*
FROM member inner join account
on member.mem_id = account.mem_id
where member.mem_id = $member_id';
答案 2 :(得分:0)
您正在比较相同的ID:“WHERE member.mem_id = account.mem_id”(我假设member.mem_id和account.mem_id引用相同的“用户”)。
你应该这样做:
$query = "SELECT member.*, account.*
FROM member, account
WHERE member.mem_id = " . $the_id;
其中$ the_id应该是您从表单中获得的数字(HTML表单,以澄清)。
希望有所帮助:)