开发者

PHP: Getting recipient id

开发者 https://www.devze.com 2023-01-23 08:45 出处:网络
Hey, so I have a recipient field in my form you can type a user´s fullname in, example \"john derek\".

Hey, so I have a recipient field in my form you can type a user´s fullname in, example "john derek".

Now i have exploded this into $firstname and $lastname

list($firstname, $lastname) = array_map('ucfirst', explode(' ', $recipient, 2));

How can i check in the database if there's any full match, take the id.

table users has column "firstname" and "lastname"

If theres half match, if only there exists firstname (john) or lastname(derek) and not both, echo "Did you mean: John Derek?";

$qur = mysql_query('
 SELECT id, firstname, lastname, 
 (firstname = "$firstname" AND lastname = "$lastname") AS full FROM users 
 WHERE (fi开发者_运维技巧rstname = "$firstname" AND lastname="$lastname") 
 OR (firstname LIKE "$firstname%" AND lastname LIKE "$lastname%")
 ORDER BY (firstname = "$firstname" AND lastname="$lastname") DESC');
 $get = mysql_fetch_array($qur);
 echo $get["full"] ."<br>";

Im not getting anything in this, even that $firstname is "John" and $lastname is "Derek"

also tried:

echo $get["id"];
echo $get["lastname"]
echo $get["firstname"]

Seems like it dont find anything? What is wrong?


The simplest way is to do a LIKE query:

 SELECT id, firstname, lastname FROM users 
 WHERE firstname LIKE "$firstname%"
 AND lastname LIKE "$lastname%"

(Don't forget sanitizing the variables, of course)

User input that this would match:

Jo De
J Derek
John D

It would give you a result set back. If, for a search for John Der, there is a John Derek and a John Der though, there's no guarantee that John Der will come first. To achieve that, you'd have to check for literal matches first:

 SELECT id, firstname, lastname, 
 (firstname = "$firstname" AND lastname="$lastname") AS full FROM users 
 WHERE (firstname = "$firstname" AND lastname="$lastname") 
 OR (firstname LIKE "$firstname%" AND lastname LIKE "$lastname%")
 ORDER BY (firstname = "$firstname" AND lastname="$lastname") DESC

this will give the full match first, partial matches second.

It may need further tweaking, but it should be a start.

0

精彩评论

暂无评论...
验证码 换一张
取 消