Using the power of PDO, implementing variable SQL query with bindParam and executing it within

After making the switch from using mysql_ functions to PDO, I've encountered a bit of a challenge that I'm hoping to get some help with.

The issue I'm facing is with the search query. Currently, I have it set up like this:

$result = $DB->prepare('SELECT * FROM `posts` WHERE `title` LIKE :searchterm OR `tags` LIKE :searchterm LIMIT '.$start.', '.MAX_ITEMS);
$result->bindParam(':searchterm',$searchterm);
$result->execute();

Given that the query size can vary based on the user's search input, how can I modify it to achieve something like this:

$array = explode(' ',$searchterm);
$query = 'SELECT * FROM posts WHERE ';

foreach($array as $word){
    if( strlen($word)>2 ){
        $query .= ' (`title` LIKE "%'.$word.'%" OR `tags` LIKE "%'.$word.'%") AND';
    }
}
$query = substr($query,0,-3);
$query .= 'ORDER BY `date` DESC';

// How do I use bindParam() in this scenario?

I would really appreciate a small example to help me get started.

Thank you! ;)

Answer №1

$data = array();
$arr_query = array();

$tab = explode(' ',$searchterm);
$query = 'SELECT * FROM posts WHERE ';

foreach($tab as $value){
    if( strlen($value)>2 ){
        // My apologies for this, but I believe using implode() would be more efficient
        $arr_query[] = '(`title` LIKE ? OR `tags` LIKE ?)';

        $data[] = '%'. $value .'%';
        $data[] = '%'. $value .'%';
    }
}
$query .= implode(' AND', $arr_query);
$query .= ' ORDER BY `date` DESC';

$res = $pdo->prepare($query);
$res->execute($data);

Limitations mentioned in the initial example need to be safeguarded.

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

Form using Ajax technology, including two drop-down menus sourced externally

Is there a way to automatically populate a second drop-down list with all models once a selection is made in the first drop-down on a form? Below is the code snippet: <form> <div class="landing_quote_left"> ...

Tips for implementing Memcached with Doctrine2 and ZF2

After following the instructions in this article: , my code, directories, and configuration are all set up accordingly. My current config file resembles the following: <?php namespace Game; return array( // <snip> // Doctrine config ...

Issue with anchor tag not functioning properly within toggle div

Can you please help me troubleshoot why the anchor tag is not functioning properly within my div elements? When I click on the first div, the second div is displayed but the anchor tag inside the first div does not seem to be working. <script> $(&ap ...

Exploring the connection of tables across various databases using CI DataMapper ORM

I tried searching for a solution, but unfortunately, nothing proved to be helpful. This question was regarding utilizing multiple databases with datamapper, however, I am already using that approach. User model: class User extends DataMapper { var $p ...

Challenges with dynamically adding rows using jQuery

I am trying to create a dynamic form that allows users to select a project and then populates tasks based on the selected project from a database query. The user can then enter hours for each task, which are updated based on the project id and task id comb ...

Utilizing Laravel Eloquent to perform substring queries in SQL

Struggling with my SQL query in Laravel 8. I'm aiming to extract the first character from the column name, but only for distinct values. These characters will be linked to glossary definitions. $chars = DB::table('parts') ->di ...

Ensuring the validity of a file input through AJAX in a form built with Laravel

I am facing an issue with validating an image field in a Laravel form using AJAX. The field always appears to be empty even after selecting a file. How can I use ajax validation to check if the file input is empty or not? Here is the form code: {{ Form:: ...

Unable to obtain the Twilio "call recording" URL

Currently, I am working on an online campaign management system that utilizes Twilio. Each campaign in the system will have a unique Twilio number and target number. When a call is made to a specific Twilio number assigned to a campaign, it will be forward ...

Custom PHP contact form for Wordpress

I've been working with code from a different source and it's definitely not the usual HTML/PHP setup I'm used to. Wordpress seems to have its own way of doing things. Right now, I'm struggling to make the contact form's PHP include ...

The readyState of Ajax is consistently anything but 4

I have encountered an issue with my JavaScript code. I am running these codes in order to display data based on user input. Despite there being no error connection and the connection happening properly, whenever I enter a name it always goes into the else ...

Using Yii: Steps to incorporate a CSS class into a dropdown menu

I am currently working with Yii 1.1.10 and I am interested in learning how to incorporate a CSS class into a dropdown list while using a CActiveForm. For instance, how could I go about adding a CSS class to the following dropdown list? <?php echo $for ...

Shade of a row within a PHP table

I have a table that is populated with data from a database. Is there a way for me to dynamically change the color of a row based on certain conditions from a JSON file? For example, if the temperature exceeds a set minimum value, I want to highlight the ro ...

Enhanced Functionality: Dynamic URL Redirection using Ajax &

I want to redirect within a PHP file that is being called via AJAX. I have included the redirection code inside the file, but it doesn't seem to be working. Here is the code for the AJAX file: <?php ob_start(); include 'admin/includes/front_ ...

Setting up Algolia integration in Laravel

While attempting to install the Algolia Laravel package, I encountered an error stating: The trait 'App\AlgoliaEloquentTrait' cannot be found I followed the installation, configuration, and quickstart instructions provided in this link: h ...

Updating an element within a JSON object in PHP: A step-by-step guide

I have a JSON object that looks like this: { "fields" : [ { "name" : "news_title", "type" : "text", "value" : "old title" }, { "name" : "news_co ...

Tables that are not only responsive but also friendly to mobile

For the past week or so, I've been working on finishing up the layout for a single page. While I have managed to get the page somewhat functional, I am in need of assistance with both the original layout and ensuring it is mobile-friendly. The issue w ...

Transmitting PHP variable to JavaScript using Callback Method

I am looking to implement password validation using JavaScript along with an Ajax function. Upon successful validation, I aim to return a boolean variable (true or false) and perform specific actions in my PHP file based on the callback. Unfortunately, my ...

I'm having trouble getting my HTML button to redirect to a PHP link

I'm attempting to call a PHP script from my HTML file. Here's the snippet of my HTML code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://w ...

Guide to choosing an attribute using wildcard string search in PHP's SimpleXML library

I am struggling to figure out how to select nodes with an attribute that contains the word "Rock" using PHP's SimpleXML library. I attempted to add a wild-card character to the attribute value, but it did not work as expected. Below is a snippet from ...

Is it possible to include both the value and text of a dropdown in form.serialize?

For my project, I need to serialize the form data. However, when it comes to dropdowns, only the values are captured and not the text of the selected option. <select name='attend'> <option value="1" selected="selected">Question&l ...