MySQL选择查询,通过在搜索栏中键入多个单词从多个列中检索数据

时间:2013-01-18 18:55:43

标签: php mysql

好的,这是交易,我有一个数据库让我们说2列: “名字”和“姓氏”

当我在输入框中输入“John”之类的名称时,它将从“name”列中检索所有John。当我输入像“Doe”这样的姓氏时,它将从“lastname”列中检索所有Doe。这可以按预期工作。

但是当我输入“John Doe”时,我希望它也从两列中检索数据,因此它将返回所有John Doe。当在搜索栏中输入一个单词时,它可以正常工作,但是当我在空格后放入另一个单词时,它不会做我想要的,因为我不知道如何正确地形成查询。

这是query.php的代码:

    <?php
    require_once("config.php");
    // Fetch the data
    $searchbar = $_POST['searchbar'];

    $querymilion = "SELECT * from lms.customers where `lastname` LIKE '%$searchbar%' OR `name` LIKE '%$searchbar%'";
    mysql_query('SET NAMES \'utf8\'');
    $resultmilion = @mysql_query($querymilion);

    // Return the results, loop through them and echo
    if($fraza) {
    while($rowmilion = mysql_fetch_array($resultmilion))
    {
    ?>
    <a href="javascript:klientid()" onClick="klientid()">
    <table id="tablesz" >
    <tr>
    <td style="font-weight:bold; width: 160px; text-align:right;">ID:</td>
    <td style="width:200px;" id="getidfromsearch"><?php echo $rowmilion['id']; ?></td>
    <td style="font-weight:bold; width: 50px; text-align:right;">PESEL:</td>
    <td style="width:200px;"><?php echo $rowmilion['ssn']; ?></td>
    </tr>
    <tr>
    <td style="font-weight:bold;width: 160px; text-align:right;">Nazwisko i Imię:</td>
    <td style="width:200px;"><?php echo $rowmilion['lastname']; ?> <?php echo   $rowmilion['name']; ?></td>
    <td style="font-weight:bold;width: 50px; text-align:right;">Dow.os.:</td>
    <td style="width:200px;"><?php echo $rowmilion['icn']; ?></td>
    </tr>
    <tr>
    <td style="font-weight:bold; width: 160px; text-align:right;">Adres instalacji</td>
    <td style="width:200px;"><?php echo $rowmilion['address']; ?></td>
    <td style="font-weight:bold; width: 50px; text-align:right;">Miasto:</td>
    <td style="width:200px;"><?php echo $rowmilion['zip']; ?> <?php echo $rowmilion['city']; ?>
    </td>
    </tr>
    </table>
    </a>
    <?php

    }
    }
    ?>

这是搜索栏:

    <div id="szukaj">
    <table id="tablesz" >
    <tr>
<td class="naglowek">Szukaj klienta</td>
    </tr>
    <tr>
<td>
<form id="myForm" enctype="multipart/form-data" action="query.php" method="post"  name="myForm">
<input type="text" name="searchbar" value="" />
<input type="submit" value="Szukaj" /> 
</form>
</td>
    </tr>
    <tr>
<td>
<span id="error"></span>
<span id="result"></span>
</td>
    </tr>
    </table>
    </div>

2 个答案:

答案 0 :(得分:0)

问题是你的CODE,

如果你想制作像John Doe这样的搜索,你需要将每个单词分开并将其放入谎言中,当然这会降低查询的速度。

即:

$querymilion = "SELECT * from lms.customers 
where (`lastname` LIKE '%$John%' OR `name` LIKE '%$John%')
and (`lastname` LIKE '%$Doe%' OR `name` LIKE '%$Doe%')";

这样可以与John Doe完全匹配。

答案 1 :(得分:0)

SELECT * 
FROM  `actor` 
WHERE CONCAT( firstname,  ' ', lastname ) LIKE  "%$searchbar%"

当你的桌子增加时,这会变得很慢。但它的确有效。 如果您还希望能够将firstname lastname的顺序切换为lastname firstname,只需将其添加到Query:

OR CONCAT( lastname,  ' ', firstname ) LIKE  "%$searchbar%"