質問

I am trying to pass a parameter in my url like so: http://example.com?rep_name=JoeSmith

The database table has this structure:

+----+-------+-------+-------------+
| id | fname | lname |    email    |
+----+-------+-------+-------------+
|  1 | Joe   | Smith | joe@joe.com |
+----+-------+-------+-------------+

How can I query the table and search for users that match first & last name? Right now I am only able to query using either fname or lname. The variable $rep_name holds the parameter value, but I am not sure how I can use first & last name in the parameter and in the query since they are on separate columns.

SQL:

$sql = "SELECT id
        FROM contacts
        WHERE fname='" . mysql_real_escape_string($rep_name) . "'
       ";
役に立ちましたか?

解決

Assuming the rep name is always the first and last name appended to each other, just use CONCAT() to append them and then compare them to your value.

$sql = "SELECT id
    FROM contacts
    WHERE CONCAT(fname,lname)='" . mysql_real_escape_string($rep_name) . "'
";

I just hope all of your reps have unique first name last name combinations if this is going to be used to authenticate reps in any way.

他のヒント

Try using CONCAT a mysql function

 "SELECT id FROM contacts WHERE CONCAT(fname," ",lastname)='" . mysql_real_escape_string($rep_name) . "' "; 

CONCAT() JOINs all stuffs in between any number of , commas;

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top