SQL按帐号过滤

时间:2013-08-07 09:06:16

标签: php sql

我需要更新SQL以按我要查询的帐号进行过滤:此代码显示与& memid = 3的值相对应的帐户。我认为给$ memid一个值将限制我的过滤。如何创建一个sql,我将输入帐号,然后显示相应的帐户。

$memid = 3; // example
$sql = "SELECT member.*, account.* FROM member, account WHERE member.mem_id = 
account.mem_id AND member.mem_id = '".$memid."' ";

这是整个代码:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$memid = 3; // example
$sql = "SELECT member.*, account.* FROM member, account WHERE member.mem_id =  
account.mem_id AND member.mem_id = '".$memid."' ";

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);
?>

1 个答案:

答案 0 :(得分:0)

首先,如果您只需要检索某些字段,请不要使用*。 如果表成员和帐户表具有相同名称的字段,请使用AS表达式。 最好使用JOIN连接表 SQL示例:

SELECT a.mem_id AS memberid,a.Account_Number AS accnum, %etc.% FROM member AS a
INNER JOIN account AS b ON a.mem_id = b.mem_id 
WHERE a.mem_id = '%id%';

在mysql_fetch_array的结果中,您将获得$ row变量数组,其中包含您在AS语句中设置的唯一键:

Array ("memberid"=>"%id%","accnum"=>"%Account_Number from DB%", %etc.%)

PS:英语不是我的母语,感谢理解,并在必要时随时纠正我。