phpmyadmin 我如何在sql表中合并2列来搜索全名

ijxebb2r  于 2022-11-09  发布在  PHP
关注(0)|答案(6)|浏览(194)

我有一个带有FirstName和LastName列的mySQL数据库,目前我有一个搜索姓氏的搜索查询,当姓氏匹配时,它们将与它所在行的FirstName沿着在屏幕上显示,现在很好,我想了解的是如何使查询搜索输入到输入字段中的FullNames,请记住,我没有一个全名列的全名将是什么用户类型,下面是一个例子,我目前有什么工作!谢谢。

if(isset($_GET['name'])){   
    $raw_name=$_GET['name'];

    if(preg_match("/[A-Z | a-z]+/", $raw_name)){        
        $name=$raw_name;        
        include "connect.php";      
        //-query the database table
        $sql="SELECT userId, FirstName, LastName FROM residential2 WHERE FirstName='" . $name   ."'";
        //-run the query against the mysql query function
        $result=mysql_query($sql);
        //-count results
        $numrows=mysql_num_rows($result);

        echo "<div align=\"center\">" . $numrows . " results found for " . stripslashes($name) . "</div>";

        while($row=mysql_fetch_array($result)){         
            $FirstName =$row['FirstName'];
            $LastName=$row['LastName'];
            $userId=$row['userId']; 
            //-display the result of the array
            echo "<ul>\n"; 
            echo "<li>" . "<a href=\"index.php?id=$userId\">" . $LastName . " "  .$FirstName . "   </a></li>\n";
            echo "</ul>";
        }
    }
    else {      
        echo "<p>Please enter a search query</p>";
    }
}
polhcujo

polhcujo1#

使用concat()

$sql="SELECT userId, CONCAT(FirstName, ' ', LastName) AS fullname FROM residential2 WHERE FirstName='" . $name   ."'";

<?php
    $fullname = $row['fullname']; 
?>
xyhw6mcr

xyhw6mcr2#

非常非常简单!!

SELECT * FROM your_table WHERE CONCAT(字段1,“”,文件2)类似于“% $query %”

brgchamk

brgchamk3#

您可以执行以下操作:

$sql="SELECT userId, FirstName, LastName 
            FROM residential2 
            WHERE concat(FirstName, ' ', LastName) like '%$name%'";
q1qsirdb

q1qsirdb4#

您必须将全名拆分为名和姓,然后进行相应的搜索。以下代码片段适合您:

SELECT REVERSE(SUBSTR(REVERSE(name),INSTR(REVERSE(name),' ')+1)) AS first_name,
REVERSE(SUBSTR(REVERSE(name),1,INSTR(REVERSE(name),' '))) AS last_name

希望能有所帮助。

ao218c7q

ao218c7q5#

$frnd_name = trim(preg_replace( "/[ ]+/", " ", $_GET['frnd_search'] ) );
$arr = explode(" ", $frnd_name, 2);

if(!empty($arr[1]))
    $sql_where = "name LIKE '%".$arr[0]."%' AND lastname LIKE '%".$arr[1]."%'";
else
    $sql_where = "name LIKE '%".$arr[0]."%' OR lastname LIKE '%".$arr[0]."%' OR username LIKE '%".$arr[0]."%' OR email LIKE '%".$arr[0]."%'";

$sql = "SELECT name,lastname,username,email FROM user WHERE ".$sql_where;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "".$row['name']." ".$row['lastname']."<br>";
    }
}
z4iuyo4d

z4iuyo4d6#

SELECT lname, fname FROM TABLE where CONCAT(fname, ' ', lname) LIKE '%$fullname%'

相关问题