1

我有一个表单,它接受用户输入的多个参数。然后它们用于搜索和检索记录。查询需要连接多个表,但由于参数值来自用户,我的代码目前正在创建具有交叉产品的多条记录,即具有多个地址的同一个人。

这是我的代码:

if( $_POST["submit"] ) {

if (!($stmt =$mysqli->prepare(" SELECT DISTINCT Fname, Minit, Lname, EMPLOYEE.Phone, Address, Sname, Saddress, Dno, Hourly
    FROM EMPLOYEE, DEPARTMENT, LOCATION
    WHERE EMPLOYEE.Fname=? OR EMPLOYEE.Lname=? OR EMPLOYEE.Dno=? OR LOCATION.Store_num=?"))) {      
print "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ssii",$_POST['Fname'], $_POST['Lname'], $_POST['Dno'], $_POST['Store_num'])) {
print "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
    print "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }       
$stmt->store_result();
if (!$stmt->bind_result($Fname,$Minit,$Lname,$Phone,$Address,$Slocation,$Saddress,$Dno,$Hourly)) {
         print "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if ($stmt->num_rows == 0){
    print "No results were found for the following search <p>"
    .$_POST['Fname'].$_POST['Lname'].$_POST['Store_num'].$_POST['Dno']."</p>";
}

else {
    print "<table border=2 cellpadding=4>

        <tr bgcolor=white>

        <th>First Name</th>

        <th>Middle Initial</th>

        <th>Last Name</th>

        <th>Phone</th>

        <th>Address</th>

        <th>Store</th>

        <th>Store Location</th>

        <th>Dept #</th>

        <th>Hourly Rate</th>

        </tr>";

while ($stmt->fetch()){

    print "<tr><td>".$Fname."</td><td>".$Minit."</td><td>".$Lname.

    "</td><td>".$Phone."</td><td>".$Address."</td><td>".$Slocation."</td>
    <td>".$Saddress."</td><td>".$Dno."</td><td>".$Hourly."</td></tr>";
    }

print "</table>";
}
4

1 回答 1

0

解决此问题的一种方法是根据传入的参数动态形成 SQL 查询。如果用户试图过滤该值,您似乎只想加入 LOCATION 表。如果你加入它并且他们没有传递一个值,它可能会强制返回额外的行。

另请注意,我假设这Dno是加入 DEPARTMENT 和 EMPLOYEE 的关键,这Store_num是加入 LOCATION 和 DEPARTMENT 的关键 - 如果不是,只需将它们更改为您的密钥。我没有从您的问题中获得的一些信息,但是以下概念应该是您需要做的。

$fromClause = '';
$whereClause = '';

// If they have filtered on Store_num, add the relevant bits to the query
$if(isset($_POST['Store_num'])) {
    $fromClause = " INNER JOIN LOCATION ON LOCATION.Store_num = DEPARTMENT.Store_num ";
    $whereClause = " OR LOCATION.Store_num = ?";
}

$query = '
SELECT 
    DISTINCT Fname, Minit, Lname, EMPLOYEE.Phone, Address, Sname, Saddress, Dno, Hourly 
FROM 
    EMPLOYEE 
INNER JOIN 
    DEPARTMENT ON DEPARTMENT.Dno = EMPLOYEE.Dno
' . $fromClause . '
WHERE 
    EMPLOYEE.Fname=? OR EMPLOYEE.Lname=? OR EMPLOYEE.Dno=?
' . $whereClause;
于 2012-11-26T01:19:23.010 回答