Felipe Bueno Felipe Bueno - 6 months ago 22
MySQL Question

How to select all results that contain first and last name?

Very specific question, how can I make a select from a

$_SESSION
that contains the first, middle and last name, only the first and last name?

Example:

The output from
$_SESSION['NET']['USER']['NAME']
is
'Robert Pasha Biceps'


What I really need on a
SELECT
is ALL that contains
'Robert Biceps'


$pdo = new \PDO('mysql:host=localhost;dbname=workflow_teste', 'root', '');

$pdo->setAttribute(\PDO::ATTR_ERRMODE , \PDO::ERRMODE_EXCEPTION);

$string = "SELECT * FROM foo WHERE fooname LIKE '".$_SESSION['NET']['USER']['NAME']."' ";

$statement = $pdo->prepare($string);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor();

echo '<pre>';
var_dump($result);
die;


The
var_dump
only shows the results that have the entire name on it, but some people submit only the first and last name, and I need that results also...

Any ideas?

Answer

You need to split the name into parts and only use first and last part in your SQL query.

$name = explode(' ', $_SESSION['NET']['USER']['NAME']);
$firstname = $name[0];
$lastname = $name[count($name)-1];
$string = "
    SELECT *
    FROM foo
    WHERE
        fooname LIKE '".$firstname." % ".$lastname."' OR
        fooname = '".$firstname." ".$lastname."'
";

From these rows:

Robert Pasha Biceps
Robert Biceps
Robert Middlename Biceps
Robert Pasha
Pasha Biceps
Robert Pasha Triceps
Robert Other Biceps
Roberto Pasha Triceps

the query with the name "Robert Pasha Biceps" will select

Robert Pasha Biceps
Robert Biceps
Robert Middlename Biceps
Robert Other Biceps

Also, you should look up and use prepared statements, to prevent a "Bobby tables situation".