I’m building a Telegram bot for my cafe to handle table bookings and show daily specials. The bot runs on Heroku with PHP and connects to a MySQL database hosted elsewhere. Everything works perfectly until I add the database connection code.
<?php
header('Content-Type: application/json');
$input = file_get_contents("php://input");
$webhook_data = json_decode($input, true);
$connection = mysqli_connect('host', 'user', 'pass', 'database');
$sql = "SELECT * FROM daily_specials ORDER BY position ASC" or die("Query failed: " . mysqli_error($connection));
$query_result = mysqli_query($connection, $sql);
$data_array = array();
while ($record = mysqli_fetch_array($query_result, MYSQLI_ASSOC)) {
$data_array[] = array(
'category' => $record['CATEGORY'],
'dish_name' => $record['DISH']
);
}
$daily_menu = json_encode($data_array);
$msg = isset($webhook_data['message']) ? $webhook_data['message'] : "";
$msg_id = isset($msg['message_id']) ? $msg['message_id'] : "";
$chat_id = isset($msg['chat']['id']) ? $msg['chat']['id'] : "";
$first_name = isset($msg['chat']['first_name']) ? $msg['chat']['first_name'] : "";
$last_name = isset($msg['chat']['last_name']) ? $msg['chat']['last_name'] : "";
$user_name = isset($msg['chat']['username']) ? $msg['chat']['username'] : "";
$timestamp = isset($msg['date']) ? $msg['date'] : "";
$user_text = isset($msg['text']) ? $msg['text'] : "";
$user_text = trim($user_text);
$user_text = strtolower($user_text);
$today = date('Y-m-d');
$bot_reply = '';
$menu_data = $record['schedule'];
if(strpos($user_text, "/start") === 0 || $user_text=="hello")
{
$bot_reply = "Hello $first_name $last_name, welcome to our Cafe Bot! Type 'booking' to reserve a table or 'specials' to see today's menu!";
}
elseif($user_text=="booking")
{
$bot_reply = "How many people for your reservation on $today?";
}
elseif($user_text=="specials")
{
$bot_reply = "Today's specials: $daily_menu";
}
else
{
$bot_reply = "Sorry, I don't understand that command!";
}
$params = array('chat_id' => $chat_id, "text" => $bot_reply);
$params["method"] = "sendMessage";
echo json_encode($params);
?>
When I remove all the MySQL code, the bot responds normally. But with the database queries included, it stops working completely. Can someone help me figure out what’s wrong? Is it even possible to use MySQL databases with Telegram bots like this?