I cannot access my user-defined function strip_punctuation() within my subsequent sql query. I'm using PHP and PDO.
I keep getting one of two errors no matter how I attempt this:
MySQL error 2014 Cannot execute queries while other unbuffered queries are active
OR
MySQL error 1305 Function does not exists.
I've tried using prepare(), exec() and various other combinations, but no matter what I do I either get empty results or one of the two errors above.
Here is my function
(Note: $this->PROJECT_DB->connection-> is equivalent to PDO->connection->)
public function searchAutoComplete($searchString){
$this->PROJECT_DB->connection->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
$sql ="DROP FUNCTION IF EXISTS strip_punctuation;
DELIMITER | CREATE FUNCTION strip_punctuation($input text) RETURNS text
BEGIN
DECLARE $stringValue VARCHAR(100);
SET $stringValue = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE($input,'.',''),',',''),'?',''),'@',''),'#',''),'$',''),'%',''),'^',''),'*',''),'<',''),'>',''),':',''),'
',''),')','');
RETURN $stringValue;
END; | DELIMITER ;";
//$query = $this->PROJECT_DB->connection->exec($sql);
$query = $this->PROJECT_DB->connection->query($sql);
if($query===false){
throw new Exception('Project.model: searchAutoComplete: Error with strip_punctiation function. Error was: ' . print_r($this->PROJECT_DB->connection->errorInfo(),true) . ';<br />SQL was: <br />' . $sql);
}
$sql=" SELECT strip_punctuation('something@else.com') AS FoundWord;";
$query = $this->PROJECT_DB->connection->query($sql);
if($query===false){
throw new Exception('Project.model: searchAutoComplete: Error with select query. Error was: ' . print_r($this->PROJECT_DB->connection->errorInfo(),true) . ';<br />SQL was: <br />' . $sql);
}
$results = $query->fetchAll(PDO::FETCH_OBJ);
return $results;
}
When I run both queries (defining the function and the simple select statement) in Sequel Pro (a sql editor program), I have no problems. I've tried running both statements in one query and I get no results returned.
I'm running PHP 5.3.29 with pdo_mysql 5.5.40-36.1
Assuming your function is well defined (because you did test it), the 2014 error is caused by attempting to run a query before fetching the results of an earlier query. You have to invoke PDO's fetch method after defining the function as well, to fetch MySQL's response.
TL;DR: Just add
$query->fetchAll();
after your first query, that should do the trick.