Database query not working in Telegram bot using mysqli connection

I’m working on a Telegram bot project and running into issues when trying to fetch information from my MySQL database.

I have a database table called university with three columns: event_date, weekday, and classes. My goal is to retrieve today’s class schedule from this table and send it to users through the bot.

Here’s the database code I’m using:

<?php

// Database connection setup
$connection = new mysqli('host', 'username', 'password', 'database_name');

// Get current date
$today = date('Y-m-d');

// Query to fetch schedule data
$sql = "SELECT classes FROM university WHERE `event_date` = '$today'";
$result = $connection->query($sql);
$data = $result->fetch_assoc();

// Bot response logic
if($userMessage == "schedule")
{
    $currentDate = date('Y-m-d');
    $response = $data;
    sendTelegramMessage($userId, $response);
}

The bot responds to other commands fine, but when it tries to pull data from the database, nothing gets sent back to the user. I’ve double checked my database connection settings and the table has data for today’s date. Can anyone spot what might be causing this issue?

The main issue here is that your database query is executed outside of the bot’s response logic. This means it runs only once when the script loads, rather than when the user requests the schedule. You should move the database query inside the ‘if’ statement that handles the schedule command. Additionally, instead of passing the entire array from fetch_assoc() directly to sendTelegramMessage, extract the actual classes value. Change the code to use $response = $data[‘classes’] and add error checking to ensure the query returns results before sending a response.

also check if you’re properly escaping that date variable - using ‘$today’ directly in the query like that can cause issues. try using prepared statements instead or at least mysqli_real_escape_string(). and make sure to test if $result actually returns anything before calling fetch_assoc() on it