Perform a fulltext search using PDO to retrieve results based on partial matches of keywords within a database column

I'm attempting to search two columns in a database with this small PDO statement:

$search = $pdo->prepare("
    SELECT * FROM books WHERE MATCH (title, author) AGAINST (? IN BOOLEAN MODE);
");

$search->execute(array('*' . $_POST['search'] . '*'));

For example, if our string is:

Harry Potter and the Philosopher's Stone by J.K Rowling

(This book title and author are stored in a db using MyISAM as storage engine)

If I search for Har (the first part of the Harry keyword), I can find the result I want. However, typing rry (the last part of the Harry keyword) does not return the desired result.

Furthermore, is there a way to display my desired result even when the keyword is misspelled, such as Harru instead of Harry (with minimal use of PHP)?

Thank you for your assistance! :D

Answer №1

If you don't want to use MATCH against you, a simple solution is to use LIKE. If you need to search in multiple columns at once, bind the $_POST['search'] to more than one parameter for it to work effectively.

Try this updated code:

$search = $pdo->prepare("
    SELECT * FROM books WHERE title LIKE :title OR author LIKE :author;
");

$search->execute([
    'title' => '%' . $_POST['search'] . '%',
    'author' => '%' . $_POST['search'] . '%'
]);

Answer №2

Regarding performance concerns, I recommend trying out regular expressions as a solution.

SELECT * from books
WHERE title REGEXP "[[:<:]].*rr.*[[:>:]]"
OR author REGEXP "[[:<:]].*rr.*[[:>:]]";

This code snippet will capture words like Harry, Hurry, Harr, etc., giving you room to further refine your search.

If needed, refer to https://dev.mysql.com/doc/refman/5.6/en/regexp.html for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should be taken to mitigate the impact of a SQL-Injection attack?

As I embark on learning database designing and PHP, my main concern is SQL injection. In the event that it does happen, I am curious if there is a way to reverse it automatically, reset affected accounts, close hacked databases, or even find a way to aut ...

Can the $_SESSION[balance] be updated automatically?

On each login, I retrieve the value of $_SESSION[balance] from a MySQL database. Is there a way to update this value in the client's browser every 5 minutes without refreshing the page? Could AJAX be used for this purpose? I apologize if my question ...

Run an ajax function when a variable is populated with data

My current dilemma involves a session variable email=$_GET['email'];. I am seeking a way to trigger an ajax function only when this variable is available, and to set it to do nothing if the variable is not present. What is the technique for invo ...

Move and place, editing tools

Is it possible to create a drag-and-drop editor similar to the one found in the form editor on wufoo.com? ...

Utilizing the WordPress the_content filter in the front-page.php template

Can you figure out why the the_content filter isn't being applied when using the front-page.php file? The following code is not running when front-page.php is used; it works with index.php, page.php etc.. function another_filter_name($content){ ...

Getting the raw exception message in Laravel without any HTML formatting can be accomplished by accessing the `

When interacting with the Laravel backend, I frequently make ajax requests. While processing the request data on the backend, there are instances where exceptions are thrown. By default, Laravel generates HTML pages with exception messages. However, my r ...

Developing a procedure to manipulate multiple variables

I am a beginner in PHP and I am struggling to find the right resource online to clear my confusions. Here is my issue: I am trying to create a function that takes a variable name like Thief's Wit (4) And converts it to thiefswit.jpg Here is the c ...

Tips for removing special characters from HTML?

I'm currently grappling with the concept of the filter My situation is as follows: $htmlData includes a user-entered html string formatted like this $htmlData = array('<em>test</em>', 'text here','\n') ...

Using Node, Express, and MYSQL to Fetch JSON Data from a MYSQL Database

I have saved JSON data in a database under the accessPoint field, and it appears like this: {"mode": "client", "rate": 0, "ssid": "RMG", "signal": 0, "channel": 0, "password": "", "username": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

Utilizing PHP functions to eliminate characters beyond a specified phrase with Strip, Trim, and Explode

I am facing an issue with a form where a cookie value is being duplicated in a hidden input box causing problems with our reporting software. The cookie holds the user's login email address, and I need to find a way to prevent this duplication from ha ...

Transfer information via ajax to yii controller

Thank you all for your assistance, it has been incredibly helpful. I am new to yii and feeling a bit overwhelmed at the moment. I have created a jQuery script to validate a form and then send it to my controller to process and save in the database. Howev ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Is it possible to refer to the same database table in Laravel?

I have a rather intriguing query - is it possible to reference the same database table in Laravel? I have a model called Account with a corresponding table named accounts. Each account can contain multiple subaccounts, and I am aiming to establish a hierar ...

Tips for creating personalized SEO-friendly URLs using .htaccess or PHP

I am trying to transform a URL http://www.domain.com/song.php?id=MkJoY2JyX3FWY2Q3b09nUFlZTkdDQT09 Into the following format: domain.com/song/MkJoY2JyX3FWY2Q3b09nUFlZTkdDQT09? What steps do I need to take in order to achieve this transformation? Any su ...

What is the best way to retrieve the parameter of ng2-file-upload using endback?

I am attempting to retrieve a parameter using PHP in order to save it into a folder. However, my code is not working as expected. Here is the code snippet: Using the Ionic framework this.uploader.onBeforeUploadItem = (item: any) => { this.uploader ...

Is Laravel sanctum token persisting even after being removed in certain routes on a live server?

I've encountered an issue with Laravel Sanctum while creating an API. It works perfectly fine on localhost, but when I deploy it to a live server, the following problem arises: When accessing routes under middleware like this: Route::group([&apos ...

Determine unique dates from DateTime values in MySQL

I need to extract data from a database table that logs requests with an IP address column and a timestamp. My goal is to determine the number of days a specific IP address has made requests. I am currently using Laravel's query builder for this task. ...

Implementing ajax functionality to dynamically insert various user inputs upon a button click

I'm searching for resources or materials that explain how to use jQuery and AJAX to create a feature where multiple inputs can be added to a form with just one click. Google's Gmail client is a perfect example of this functionality, as it enables ...

Create an .htaccess RewriteRule that can generate a URL with two parameters in any order

I am facing an issue with the URL structure containing 2 parameters https://mywebsite.com/folder/subfolder/page.php?id=999&title=this-is-a-test I require a rule to transform the above URL into the following format: https://mywebsite.com/page/this-is ...