PHP表单处理 - 使用多个用户输入连接表

时间:2012-11-26 01:04:06

标签: php mysql sql

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

这是我的代码:

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>";
}

1 个答案:

答案 0 :(得分: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;