phpmysqlsqlstring-concatenationmysql-real-escape-string

Search for First & Last Name in table from URL Parameter


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) . "'
       ";

Solution

  • 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.