The first thing you should do is increase the
memory_limit for php either inside your php.ini (search for
memory_limit = 128M and set it to a higher value. Do not set the value TOO high though or a few requests will result in using all the memory of your server if the scripts are not efficient in the usage. Or you can raise the limit on the fly using
ini_set('memory_limit', '256M'); if the ini_set function is not disabled (Usually hosting providers disable so resources are not abused).
Increasing your memory limit in PHP will only temporarily solve your problem if your database is growing.
The way you are using your query is bad architecture. Queries should never be executed without a LIMIT, especially for large data sets.
There are a couple of things you need to note here, other than raising the already low
memory_limit. The problem you are currently having (if it is true that the query executed by itself returns a response quickly) is just a matter of allocating enough space for the resulting array/object and its converted string in memory; yet, other problem may cause this now or in the future. I could identify a few here to help you fix this once and for all.
1- Add a limit and a page parameter to your request so you can get the results paginated.
2- Use proper indexing in MySQL for fields you are searching by. It is preferable to have a Full Text index rather than a regular B-Tree index if you are searching in varchar or text fields as it seems you are doing.
Full-Text Search Functions
3- If for some reason you cannot use Full Text search (ex: you have to use InnoDB and not MyISAM) make sure you do not use the wildcard '%' at the beginning of the string as it will not use the index properly (if using regular B-Tree index and not Full Text).
If you absolutely HAVE to use it, I would suggest shifting to Full Text search (if you want to stick to MySQL for search and not use a search engine like Apache Solr, Sphinx Search or Elastic Search to name a few.