Searching for specific patterns using MySQL and PHP - What is the best approach?

Having just started working with MySQL and PHP, I am uncertain about how to proceed. Despite reading up on pattern matching, I still find myself struggling to apply this knowledge to my specific issue.

In my database, I have a column dedicated to codes (Column 1) and another column for the corresponding meanings (Column 2). Here is an example of the data:

+---------------+-----------+
| Code          | Meaning   |
+---------------+-----------+
| A5-B10-C11-D3 | object 1  | 
| A5-B10-C50-D8 | object 2  |
| A6-B10-C11-D7 | object 3  | 
| A2-B10-C11-D9 | object 4  |
| A5-B19-C11-D7 | object 5  | 
| A1-B10-C50-D8 | object 6  |
+---------------+-----------+

I aim to create a search function that allows users to filter the first column by selecting from the following patterns:

  • Beginning with (X...) - entering 'A5' would return Objects 1, 2 & 5
  • Ending with (..X) - inputting 'D7' would retrieve Objects 3 & 5
  • Contains in succession (X Y) - typing 'A5 B10' would display Objects 1 & 2
  • Contains in any order (X Y) with Y always following X - searching 'B10 C11' would show Objects 1, 3 & 4 or 'B10 D8' would result in Objects 2 & 6
  • Contains both but without order - where Y can precede or follow X - submitting 'D7 A5' would yield Object 5.

This should provide a good starting point, bearing in mind that there may be more complex codes like B10-B10-A1-D15-C8, with the search options designed to cover all possible patterns.

Thank you in advance for your help. If my requirements are unclear, please let me know so I can provide further explanation or additional examples.

ADDITIONAL NOTE:

The solution of breaking down each code part (A5, B10, etc.) into separate rows is not suitable for my needs.

A more practical approach for me would involve organizing the data as follows:

 +-----------+-----------+-----------+-----------+-----------+
 | 1st place | 2nd place | 3rd place | 4th place | Meaning   |
 +-----------+-----------+-----------+-----------+-----------+
 | A5        | B10       | C11       | D3        | object 1  | 
 | A5        | B10       | C50       | D8        | object 2  |
 | A6        | B10       | C11       | D7        | object 3  | 
 | A2        | B10       | C11       | D9        | object 4  |
 | A5        | B19       | C11       | D7        | object 5  | 
 | A1        | B10       | C50       | D8        | object 6  |
 +-----------+-----------+-----------+-----------+-----------+

For example, the code A5-B10-C11-D3 corresponds to Object 1.

Therefore, my ideal search functionality would allow users to query using various methods and receive relevant results:

  • No order: B10 - Result: Objects 1, 2, 3, 4, 6
  • Begin with: B10 - Result: none.
  • End with: B10 - Result: none.
  • No order: A5-B10 (or A5 B10, without dash) - Result: Objects 1, 2
  • Begin with: A5-B10 (or A5 B10, without dash) - Result: Objects 1, 2
  • End with: A5-B10 (or A5 B10, without dash) - Result: none.
  • Contain both (order Y after X, w/o or w/ other characters between) B10-C11 (or B10 C11, without dash) - Result: Object 1, 2, 4.
  • etc.

Is it feasible to implement such a search system?

Answer №1

You have the option to utilize the LIKE operator for various pattern matches.

  • To find codes beginning with: WHERE code LIKE 'A5-%'
  • To find codes ending with: WHERE code LIKE '%-D7'
  • To find codes containing specific characters in succession: WHERE code LIKE '%A5-B10-%
  • To find codes containing specific characters in a particular order: WHERE code LIKE '%B10-%C11%'
  • To find codes containing specific characters in either order: This would require using OR:
    WHERE code LIKE '%D7-%A5%' OR code LIKE '%A5-%D7%'

The efficiency of these queries is compromised, except for those involving "beginning with," as they are unable to leverage indexes. If your codes exhibit a structured pattern, it may be beneficial to store them in separate columns for more targeted searches.

An alternate approach is to normalize your data by separating each part into distinct rows of another table, with a foreign key linking back to its meaning.

Codes:

Part_Num    Code    Meaning_ID
1           A5      1
2           B10     1
3           C11     1
4           D3      1
1           A5      2
2           B10     2
3           C50     2
4           D8      2

Meanings:

ID  Meaning
1   object 1
2   object 2

You can then perform tests like:

WHERE Part_Num = 1 AND Code = 'A5'
WHERE Part_Num = 4 AND Code = 'D7'

To retrieve codes in succession:

SELECT a.Meaning_ID
FROM Codes AS a
JOIN Codes AS b ON a.Meaning_ID = b.Meaning_ID AND a.Part_Num = b.Part_Num - 1
WHERE a.Code = 'A5' AND b.Code = 'B10';

To retrieve codes in sequence, but not succession:

SELECT a.Meaning_ID
FROM Codes AS a
JOIN Codes AS b ON a.Meaning_ID = b.Meaning_ID AND a.Part_Num < b.Part_Num
WHERE a.Code = 'B10' AND b.Code = 'C11';

To retrieve codes in any order:

SELECT Meaning_ID
FROM Codes
WHERE Code IN ('D7', 'A5')
HAVING COUNT(*) = 2

With the new table structure where codes are divided into separate columns, you can execute the last query as follows:

WHERE 'D7' IN (1stPlace, 2ndPlace, 3rdPlace, 4thPlace) AND 'A5' IN (1stPlace, 2ndPlace, 3rdPlace, 4thPlace)

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

Enhancing user experience by implementing dynamic text box functionality that triggers ajax load for dropdown options using a combination

Here is the task I need help with, along with the code snippet: I want to enable the author select box when both the start and end dates are filled out. The author names should be fetched dynamically from the database based on the selected start and end ...

Having difficulty retrieving raw HTML content from JSON response while utilizing import.io API through cURL

When manually accessing the import API in a browser by copying the API URL, I receive a JSON result with HTML fields containing HTML content. However, when I access the same API URL using cURL in PHP, I only get the following JSON result: {"name":"my_html" ...

Error encountered when attempting to generate a hyperlink

Whenever I try to assign hyperlinks to each image name, I keep encountering an undefined imgitem error in the hyperlink(s). Could it be that I am incorrectly placing the <a> tags? echo '<td width="11%" class="imagetd">'; if (empty($a ...

The variable is unable to transfer successfully from JavaScript to PHP using ajax

I have a code that is designed to pass the values of all checked checkboxes to a PHP file in order to delete corresponding rows from a CSV file. The checkbox values are dynamic. <tr><td><span class="custom-checkbox"><input ty ...

Enhancing Long Polling Performance with PHP and AJAX: Tips and Strategies

I have successfully implemented long polling using a standard Apache server, PHP, AJAX, and JavaScript without relying on jQuery for server communication. However, I have encountered limitations with the Apache server as it struggles to handle more than 5 ...

How can we showcase PHP variables through CKEditor?

After using the WYSIWYG CKEditor, I saved the following content into a MySQL database: <p> Here is the information that we would like to display</p> <p> &nbsp;</p> <p> Project:<?php echo $project; ?></p> I ...

Innovative approach for showcasing JSON array using checkboxes

I have created a multidimensional array using JSON. However, now I am facing the challenge of organizing groups of checkboxes in a visually appealing manner, such as separating them with horizontal bars or placing them into tables. Here is an example of t ...

Guide to automatically update mysql posts every second

Utilizing ajax, I am able to save user posts/comments into a mysql table without the need for a page refresh. Initially, there is this <div id="posts-container"></div> Next, I attempted to use Jquery load() to iterate through a table and disp ...

Could it be possible that my SQL syntax is incorrect?

Here is the code snippet I am using to insert the values $id, $str, and $name into a database: $r=mysql_query("INSERT INTO varta(id,data,name) VALUES('$id','$str','$name');"); However, I am encountering a syntax error with t ...

Utilizing localized date formatting within Joomla modules

Is there a way to display a date in the locale date/time format in Joomla? I am currently working on a module that needs to show dates. I am aware of the workaround using strftime and strtotime functions: strftime(format_string, strotime($date)); Ho ...

Guide on showing long blocks of text in MySQL without formatting restrictions

I've come across a problem that I can't seem to solve anywhere. After storing data from a topic or comment in the database, the message is stored in a longtext format. However, when the longtext shows fine in the table (with enters and multiple ...

Executing PHP code within an AJAX request

Utilizing AJAX on a website to call a PHP script that parses another page and returns the desired content has been effective for me in the past. However, this time around, when returning a portion of the page that contains PHP code, it is being displayed w ...

Having trouble displaying element with Ajax in PHP on a Wordpress template

I attempted to perform an element replacement via an ajax call, but encountered an error. Here is my code: script.js jQuery(document).on('change','.joinee-filter-month',function(e){ e.preventDefault(); var category=jQue ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

Troublesome Errors When Uploading File to S3 Using AWS PHP SDK

After trying various methods to upload a file to my S3 account, I thought I was making progress but then encountered confusing documentation and conflicting error messages. I'm taking the manual approach without using composer: require '/path/t ...

Is it possible to create an online game using JavaScript?

Hey there, I'm interested in creating a simple online game that can be played in the browser. My main question is this: if I want two players to compete against each other online, can I achieve this by using HTML for the front-end and JavaScript for t ...

Focus on a precise email alert by targeting the email identification within WooCommerce

In my WooCommerce setup, I have created custom statuses and custom emails. Currently, I am looking for a way to utilize the current email, WC_Email, as a variable in email templates instead of relying on the status. I want to include certain if statements ...

What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logi ...

a combination of MySQL connection pooling, concurrent transactions, and the use of user-defined variables

I'm currently exploring whether I have an issue with how I utilize a mySql database in an application. My setup involves nodejs, express, mysql2, and connection pooling with multiple statements queries. Additionally, there are multiple servers running ...

PHP-generated HTML often contains unnecessary and excessive indentation

I'm trying to adjust the indentation of my HTML generated by PHP, but I'm facing issues removing some unwanted indentations. Take a look at this snippet from the HTML source: <table id="structure"> <tr> <td id="navigation"> ...