The PHP PDO prepares a query but fails to execute it

I am completely new to utilizing php and pdos. A close associate of mine has actually put together a pdo class along with a few examples detailing how it can be employed, and so far, everything has been running smoothly for me. However, I have encountered an issue while attempting to perform a query that involves the utilization of the BETWEEN mysql keyword. Unfortunately, this particular query ends up returning no results at all. After setting up the mysql_query.log file, my analysis suggests that the query is successfully prepared but not executed as expected. Before delving into the specifics outlined in the log, allow me to share my code snippet:

$newSlot = array(
    "fromDate" => $db->mysql_escape_mimic($startDate->format('Y-m-d H:i:s')),
    "untilDate" => $db->mysql_escape_mimic($endDate->format('Y-m-d H:i:s'))
);

$query = "SELECT * FROM schedule_slot WHERE (startDate BETWEEN :fromDate AND :untilDate) OR (endDate BETWEEN :fromDate AND :untilDate);";
$result = $db->prepare($query);
$slot = null;
if($result == 1) {
    $result = $db->execute($newSlot);
    if($result == 1) {
      $slot = $db->fetch();
    }
}
print "slot: " . $slot["startDate"];

Here's a portion of the relevant log data (slightly tidied up):

161010 20:59:31     
2 Connect   root@localhost as anonymous on test
2 Prepare   SELECT * FROM schedule_slot WHERE (startDate BETWEEN ? AND ?) OR (endDate BETWEEN ? AND ?)          
2 Close stmt                
2 Quit  

Additionally, here is an instance from the log demonstrating a query that executed without any issues:

161010 21:01:07     
3 Connect   root@localhost as anonymous on test         
3 Prepare   INSERT INTO schedule_slot(startDate, endDate) VALUES(?,?)
161010 21:01:08     
3 Execute   INSERT INTO schedule_slot(startDate, endDate) VALUES('2016-10-11 13:35:00','2016-10-11 14:35:00')         
3 Close stmt                
3 Quit  

Please let me know if you would like me to amend the pdo code or make any other types of adjustments. As far as I am aware, the pdo class adheres to the standard conventions. Kindly inform me why my query fails to yield any outcomes.

Note: Below is the pdo class found in the dbpdo.php file:

<?php

class dbpdo {

private $_connection;
private $_statement;

public function __construct( ) {}

public function connect( $host, $username, $password, $database ) {
    $connect = 'mysql:host='.$host.';dbname='.$database.';charset=utf8mb4';
    $this->_connection = new PDO($connect, $username, $password);
    $this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->_connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}

public function __destruct() {
    if ($this->_connection)
        $this->_connection = null;
}

public function query($query){
    try {
        return $this->_connection->query($query);
    } catch(PDOException $e) {
        return "Error: " . $e->getMessage();
    }
}

public function fetch(){
    try {
        return $this->_statement->fetch();
    } catch(PDOException $e) {
        return "Error: " . $e->getMessage();
    }
}

public function prepare($query) {
    try {
        $this->_statement = $this->_connection->prepare($query);
        return 1;
    } catch(PDOException $e) {
        return "Error: " . $e->getMessage();
    }
}

public function execute($array) {
    try {
        $this->_statement->execute($array);
        return 1;
    } catch(PDOException $e) {
        return "Error: " . $e->getMessage();
    }
}

public function mysql_escape_mimic($inp) {
    if(is_array($inp))
        return array_map(__METHOD__, $inp);

    if(!empty($inp) && is_string($inp)) {
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
    }
    return $inp;
}
}

Answer №1

If you find yourself in a situation where things are not functioning correctly, consider adding these 2 lines right after your <?php tag. Many developers work on live servers where error reporting is disabled by default, leading them to believe their code is error-free when it might actually be generating numerous errors.

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);

Next, ensure that PDO is set to throw exceptions:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$newSlot = array(
                    ":f1" => $startDate->format('Y-m-d H:i:s')),
                    ":u1" => $endDate->format('Y-m-d H:i:s')),
                    ":f2" => $startDate->format('Y-m-d H:i:s')),
                    ":u2" => $endDate->format('Y-m-d H:i:s'))
                );


$query = "SELECT * FROM schedule_slot 
            WHERE (startDate BETWEEN :f1 AND :u1) 
               OR (endDate BETWEEN :f2 AND :u2)";

$result = $db->prepare($query);
// execute the prepared query using $result instead of $db
$result = $result->execute($newSlot);

$row = $result->fetch_object();

print "slot: " . $row->startDate;

By following these steps, any errors encountered will be displayed on the page or thrown as an exception if not caught, providing visibility for debugging purposes.

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

Generating assignments within the Bitrix platform

Is there a way to automatically create tasks in Bitrix from my website form submissions? Ideally, when a user submits a form on my website, can it trigger the creation of a new task in Bitrix that is then automatically assigned to a specific user? ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

Display the output based on checkbox selection using JavaScript

I am working on a feature where I need to capture checkbox inputs using JavaScript and then store them in a PHP database. Each checkbox corresponds to a specific column in the database. If a checkbox is checked, I want to insert its value into the databa ...

Showing the content retrieved from an AJAX request sent by the controller

I'm having a hard time sending my error message "From date must be set before to date" from the controller to an ajax call. The error message should be displayed in a div as a warning. The code below is not functioning properly. Controller: $respons ...

PHP listener for HTTP requests

I need to create a PHP script that is able to handle HTTP requests from the java class linked here. I attempted to use $_POST but it doesn't seem to be functioning correctly. Any assistance would be greatly welcomed! ...

Is there a way for me to extract a random set of coordinates from a particular country using this GeoJson file?

My goal is to utilize the following GeoJson file Through PHP on my server, I want to be able to retrieve a random point by calling a URL like: http://example.com/point.php?country=Argentina and having it output one random point. I am aware that the geojs ...

Secure your PHP file upload process by implementing restrictions to prevent users from uploading an unlimited number of files. Utilize

Question Update 2 : I have noticed that users can upload unlimited files and potentially take up all the disk space. How can I prevent this from happening? Update: Since no one has answered this question, is there a recommended source I could refer to f ...

The Laravel AJAX request is malfunctioning

My form uses AJAX with $.post for GET and POST requests. However, after submitting the form using $.post, my page refreshes and the validation alert in the controller does not work. The AJAX request in the controller is not functioning correctly. Form: ...

Encountering a Laravel issue within my application. Each question is followed by a subsequent question based on the provided answer. All questions and corresponding answers are stored in the database

I am brand new to Laravel and databases as I work on creating a web application for individuals facing difficulties with specific products. The app prompts users with questions and based on their answers, directs them to the next question in sequence. Each ...

Discovering the final destination URL after a redirection

Similar Question: How can I retrieve the final URL after a redirect with file_get_contents? I have been using file_get_contents('http://someurl.com/1893849') to fetch the content of a URL, but it seems that there is redirection happening. Af ...

Guide on utilizing ajax to post data when the URL parameter changes, all without refreshing the page

As the URL parameter changes, the values in my HTML also change. I am passing these values to a JSON file, but they are getting erased when the page refreshes due to the post request. I have attempted to use event.preventDefault(), however, it seems to n ...

"ddd - Determining the Optimal Location for Synchronizing with a Remote API

To ensure the functionality of my application, it is essential to regularly synchronize data from an external service, which currently happens to be an API. This requires managing multiple entities simultaneously, prompting the need for a dedicated Domain ...

Sorting by joined table

I'm having some trouble joining two tables and ordering the query results by a specific column in the table I'm joining. Everything seems to be working fine until I include ORDER BY cm.num, then I encounter the following error: Call to a member ...

Why does PHP_SELF fail when there is a $_get parameter in the URL?

Here's a scenario: My website's URL looks something like http://localhost/coursera/instructor/course.php?id=1&name=web%20development&section=overview On this particular page, there exists a form: <form action="<?php echo $_SERVER[ ...

Generate code in Yii2 using the active form

This is the code I am using in Yii2: <?= $form->field($model, 'username')->label(false); ?> <?= $form->field($model, 'password')->label(false); ?> It produces the following output: <div class="form-group fi ...

Effective ways to protect your SMS account verification from potential DDoS attacks

One of the features of my app is user registration, where users input their mobile phone numbers and other relevant data. To ensure the validity of a user before saving their information to our database, we send an SMS containing a verification code that m ...

A critical error occurred: Unhandled Exception - Attempting to call a method on a null object in the directory C:xampphtdocsshopindex.php

Help needed with code troubleshooting - encountering error message Error message: Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\shop\index.php:11 Stack trace: #0 {main} thrown in C:\xam ...

Y is not linked to X (ExpressJS / Sequelize)

I'm currently learning about NodeJS, express, and Sequelize. I encountered an issue when trying to create a book rental - the console displays "Book is not associated to Rent." After migrating the tables to the SQL database, everything seems to be in ...

Data is stored in the database without the need to fetch it through the $_POST method

Can someone explain how the variables are being inserted into the database without using $_POST to retrieve them? Is this a new feature in php5 or am I just unfamiliar with this method? <!doctype html> <html> <head> <title>< ...

How about incorporating AJAX into your HTML code?

I am currently in the process of developing an email system for a company that wishes to use it for sending emails. To achieve this, I have implemented a custom HTML editor for creating email content. My goal is to post the email contents to an external PH ...