简体   繁体   English

HTML表单值提交给PHP并进行查询

[英]HTML form values submit to PHP and query

I'm wondering if anyone has a spare set of eyes for a moment or two. 我想知道是否有一两个人有一双备用眼睛。 The problem I see lies with my issets. 我看到的问题在于我的问题。 It is ignoring the first initial isset($lastName) and seems to always choose isset($title). 它忽略了第一个初始isset($ lastName),似乎总是选择isset($ title)。 Also I should mention the values are being posted from a HTML form to ssearch against a surname or title in a DB. 我还要提到的是,这些值是从HTML表单中发布的,用于搜索数据库中的姓氏或标题。

My question is, can anyone help with the logic problem or is there another way of doing so ? 我的问题是,有人可以帮助解决逻辑问题吗? I know its prone to SQL injection too, however it's on a local DB and I'll be looking into this closely quite soon. 我也知道它很容易进行SQL注入,但是它位于本地数据库中,我将很快对其进行仔细研究。 If anyone can make suggestions I am definitely interested to hear them. 如果有人可以提出建议,我绝对有兴趣听取他们的建议。

As per suggestion the HTML form. 根据建议的HTML表单。

<form name="lookup" method="post" action="searchEmployeeList.php" autocomplete="off">
<fieldset>
    <p>Conduct a search</p>
    <table width="600">
        <tr>
            <td width="150">Surname:</td>
            <td>
                <input type="text" name="lastName" value="" maxlength="25" placeholder="Employees surname">
            </td>
        </tr>
        <tr>
            <td width="150">Title:</td>
            <td>
                <input type="text" name="title" value="" maxlength="25" placeholder="Job role">
            </td>
        </tr>
        <tr>
            <td></td>
            <!--Blank row-->
            <td>
                <input type="submit" name="submit" value="Search now">

                <input type="submit" name="show_all" value="Show all">
            </td>
        </tr>
    </table>
</fieldset>
</form>

 if (isset($_POST['lastName'])) {

 include 'DBConDetails.php';

 if (isset($lastName)) {

     $sql = "SELECT * FROM employee_data Where last_name = '".$_POST['lastName'].
     "'";
 }
 if (isset($_POST['title'])) {

     $sql = "SELECT * FROM employee_data Where title = '".$_POST['title'].
     "'";
 }

 $result = mysqli_query($con, $sql);

 if ($result - > num_rows > 0) {

     echo "<table id = 'searchResults'> < tr >
         < td > ID < /td> < td > Name < /td> < td > Age < /td><td>Title</td > < td > Years of Service < /td> < td > Salary < /td> < /tr>";

     //multiple echos plainly for readability
     while ($row = $result - > fetch_assoc()) {
       echo '<tr>';
       echo '<td>' . $row["employee_id"] . '</td>';
       echo '<td>' . $row["first_name"] . ' ' . $row["last_name"] . '</td>';
       echo '<td>' . $row["age"] . '</td>';
       echo '<td>' . $row["title"] . '</td>';
       echo '<td>' . $row["yos"] . '</td>';
       echo '<td>' . $row["salary"] . '</td>';
       echo '</tr>';

     }
 } else {

     echo "I'm afraid we could not find any matches, try editing your criteria.";
 }
 echo "</table>";


}

If anyone should come across a similar problem in the future, the issue lay with both if statements being true, which lead to both executing and the latter overwriting the first if() statement. 如果将来有人遇到类似的问题,那么问题在于两个if语句都为true,这将导致执行和后者覆盖第一个if()语句。 Should have noticed that ! 应该已经注意到了

I think you need to be checking: 我认为您需要检查:

isset($_POST['lastName']); 

instead of 代替

isset($lastName);

As the latter would be set, but be equal to some undefined value (Maybe empty string?). 因为后者将被设置,但等于一些未定义的值(也许是空字符串?)。 The same applies to your title variable. 标题变量也是如此。

First, I think it is better to check on if ($_SERVER['REQUEST_METHOD'] == 'POST') 首先,我认为最好检查if ($_SERVER['REQUEST_METHOD'] == 'POST')

See: $_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST' 请参阅: $ _POST与$ _SERVER ['REQUEST_METHOD'] =='POST'

After that, you can check the $_POST variables with isset and maybe it can be helpful to check the variables with strlen too. 之后,您可以使用isset检查$_POST变量,也许也可以使用strlen检查变量会有所帮助。 When you use strlen , with trim you can remove the unnecessary spaces. 使用strlen ,可以trim strlen不必要的空格。

Example: 例:

<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {

    if(isset($_POST['lastName']) && strlen(trim($_POST['lastName'])) > 0) {
        // Do some action
    }
}
?>

Firstly, you're overwriting your first query/conditional statement. 首先,您要覆盖第一个查询/条件语句。

What you're telling it to do is, "if this is set, do this. If this is set, then do that". 您要说的是, “如果已设置,请执行此操作。如果已设置,请执行此操作”。

What I feel you're probably looking to do is to check if both are set then passing those variables in your query in one go. 我觉得您可能想做的是检查两者是否都已设置,然后一次性将这些变量传递到查询中。

Such as and using !empty() instead of isset() : 例如,并使用!empty()代替isset()

if (!empty($_POST['lastName']) && !empty($_POST['title']) ) {

    $lastName = $_POST['lastName'];
    $title = $_POST['title'];

    $sql = "SELECT * FROM employee_data 
            Where last_name = '" . $lastName . "' 
            AND title = '" . $title . "'";
}

If the goal here is to check for one OR the other (which looks to be the case), you can modify the above code to, and using the OR operator: 如果此处的目标是检查一个另一个(看起来是这种情况),则可以使用OR运算符将上面的代码修改为:

if (!empty($lastName) || !empty($title) ) {

    $lastName = $_POST['lastName'];
    $title = $_POST['title'];

    $sql = "SELECT * FROM employee_data 
            Where last_name = '" . $lastName . "' 
            OR title = '" . $title . "'";
}

and getting rid of: 并摆脱:

if (isset($title)) {

    $sql = "SELECT * FROM employee_data Where title = '" . $title . "'";
}

Sidenote: The OR - || 旁注:该OR - || operator can also be used in a PHP conditional statement. 运算符也可以在PHP条件语句中使用。 && is AND ; &&AND ; choose the one that is fitting for what you wish to achieve. 选择一个适合您想要实现的目标。

If my above throws you an error because of a character that MySQL is complaining about, such as apostrophes, then you will need to escape your data with mysqli_real_escape_string() . 如果我的上述操作因MySQL抱怨的字符(例如撇号)而引发错误,那么您将需要使用mysqli_real_escape_string()来转义数据。

Sidenote: If you're going to use the above, make sure you're connected to your database first, and placing include 'DBConDetails.php'; 旁注:如果要使用上述内容,请确保首先连接到数据库,并放置include 'DBConDetails.php'; as your first line above anything. 作为第一行。 It's usually good to be connected first. 首先连接通常很好。

Plus, your code is prone to an SQL injection. 另外,您的代码易于进行SQL注入。 Use a prepared statement: 使用准备好的语句:

Plus, there is no opening PHP tag before if (isset($_POST['lastName'])) { statement; 另外, if (isset($_POST['lastName'])) {语句之前没有打开的PHP标记。 if that is your actual code. 如果那是您的实际代码。

It should read as 它应显示为

<?php 
    if (isset($_POST['lastName'])) {
...

Footnotes: 脚注:

DBConDetails.php is unknown as to which MySQL API you're using. DBConDetails.php您正在使用哪个MySQL API, DBConDetails.php You need to use the same API from connection to querying. 从连接到查询,您需要使用相同的API。 Different MySQL APIs do not intermix. 不同的MySQL API不会相互混合。

Check for errors against your query also: 还针对您的查询检查错误:


If you want to seperate your submit buttons' actions 如果您想分开提交按钮的操作

<input type="submit" name="submit" value="Search now">
<input type="submit" name="show_all" value="Show all">

You will need to use seperate conditional statements and using the related name attribute. 您将需要使用单独的条件语句并使用相关的name属性。

Ie: 即:

if (isset($_POST['submit'])) {
// do something, as in include other conditionals, code etc.
}

and

if (isset($_POST['show_all'])) {
// do something, as in include other conditionals, code etc.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM