I finally managed to figure this out, see my answer.
The code below should return entries in a mysql database based on presence of all search terms across two fields, as well as match on a max distance from the client. This concept worked well before I turned it into PDO, and in fact I got it working with PDO where I had temporarily left out everything after username = pb in the mysql query, and had only $query->execute($searcharray); in the execution. But when adding the rest, I get no results if using one search word, and if more than that I get:
Response from server: Error: SQLSTATE[HY093]: Invalid parameter number
Here´s the code:
$searcharray = explode(',', $search);
$tests = array_map(function($word)
{
return "CONCAT(searchmessage, subject)
LIKE ?";
}
, $searcharray);
$where = implode(' AND ', $tests);
function addPercentage(&$value,$key)
{
$value = "%".$value."%" ;
}
array_walk($searcharray,"addPercentage");
$query=$conn->prepare("SELECT
username,sender,message,subject,timestamp,threadid,msgtype FROM Messages
WHERE $where AND username ='pb' AND
(6371 * acos (cos ( radians(?) )
* cos( radians( Messages.latitude ) )
* cos( radians( Messages.longitude ) - radians(?) )
+ sin ( radians(?) )
* sin( radians( Messages.latitude ) )
))
< ?
ORDER BY timestamp");
$query->execute (array($searcharray,$latitude,$longitude,$latitude,$visibledistance));
$sth = $query->fetchAll(PDO::FETCH_ASSOC);
I have the feeling that the (?) values in the original formula should look differently when in a PDO call, and that the way I execute it with $searcharray containing multiple values combined with the single values following it ($latitude...) is not right.
As requested, a little more detail. This code works:
$searcharray = explode(',', $search);
$tests = array_map(function($word)
{
return "CONCAT(searchmessage, subject)
LIKE ?";
}
, $searcharray);
$where = implode(' AND ', $tests);
function addPercentage(&$value,$key)
{
$value = "%".$value."%" ;
}
array_walk($searcharray,"addPercentage");
$query=$conn->prepare("SELECT
username,sender,message,subject,timestamp,threadid,msgtype FROM Messages
WHERE $where AND username ='pb' ORDER BY timestamp");
$query->execute($searcharray);
$sth = $query->fetchAll(PDO::FETCH_ASSOC);
So if $search = "tent,kat", $where will become
CONCAT(searchmessage, subject) LIKE ? AND CONCAT(searchmessage,
subject) LIKE ?
And these two words will be in the $searcharray with % signs around them.
Any idea what I´m doing wrong?