I’m building a Telegram bot for my cafe using PHP on Heroku with a MySQL database hosted on another server. The bot should handle table bookings and show daily specials. However, whenever I add MySQL connection code, the entire bot stops working. Without the database part, everything runs perfectly.
Here’s my current code:
<?php
header('Content-Type: application/json');
$input = file_get_contents("php://input");
$data = json_decode($input, true);
$connection = mysqli_connect('server', 'user', 'pass', 'database');
$sql = "SELECT * FROM daily_specials ORDER BY position ASC";
$result = mysqli_query($connection, $sql);
$items = array();
while ($record = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = array(
'category' => $record['CATEGORY'],
'dish_name' => $record['DISH']
);
}
$daily_menu = json_encode($items);
$msg = isset($data['message']) ? $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'] : "";
$user_text = isset($msg['text']) ? $msg['text'] : "";
$user_text = strtolower(trim($user_text));
$today = date('Y-m-d');
$reply = '';
if(strpos($user_text, "/start") === 0 || $user_text=="hello") {
$reply = "Welcome $first_name! Type 'booking' to reserve a table or 'specials' to see today's menu!";
}
elseif($user_text=="booking") {
$reply = "How many people for $today?";
}
elseif($user_text=="specials") {
$reply = "Today's specials: $daily_menu";
}
else {
$reply = "Invalid command!";
}
$params = array('chat_id' => $chat_id, "text" => $reply);
$params["method"] = "sendMessage";
echo json_encode($params);
?>
What could be causing this issue? Can MySQL be used with Telegram bots or is there a compatibility problem?