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?
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".
you can use from % in your SQL:
$string = "SELECT * FROM foo WHERE fooname LIKE '%".$_SESSION['NET']['USER']['NAME']."%' ";
With this way if use type each section of name can see on result.
you need to explode your session and convert it as per your requirement and pass it to query
$array = explode(' ', $_SESSION['NET']['USER']['NAME']);
$fooname = isset($array[0])?$array[0]:""." ". isset($array[2])?$array[2]:"";
and use this $fooname
in your mysql query.Your sql will be like :
$sql = "SELECT * FROM foo WHERE fooname LIKE '%".$fooname."%' ";