Fetching MySQL data for a restaurant's Telegram bot

I’m creating my first Telegram bot for my restaurant. It’s supposed to handle reservations and show the daily menu. The bot is built with PHP on Heroku and uses a MySQL database on a separate server.

Here’s a snippet of my code:

$link = mysqli_connect('server', 'user', 'pass', 'db');
$query = "SELECT * FROM daily_menu ORDER BY item_order ASC";
$result = mysqli_query($link, $query);

$menu_items = array();
while ($row = mysqli_fetch_assoc($result)) {
  $menu_items[] = array(
    'category' => $row['CATEGORY'],
    'dish' => $row['DISH']
  );
}
$menu_json = json_encode($menu_items);

// Bot logic here
if ($user_message == "menu") {
  $bot_response = "Today's menu: $menu_json";
}

The bot works fine without the MySQL part, but it breaks when I add the database code. Is it possible to use MySQL with a Telegram bot? What might be causing this issue? Any help would be great!

Have you considered using a connection pooling solution? It can help manage database connections more efficiently, especially in a cloud environment like Heroku. Also, make sure you’re properly closing your database connections after each query to prevent resource leaks. For debugging, try adding some logging statements to track the execution flow and pinpoint where exactly the bot is breaking. Lastly, consider using prepared statements for your queries to enhance security and performance. These practices have helped me maintain stable database connections in similar setups.

hey, i had similar probs. check ur firewall settings on the mysql server. maybe it’s blocking heroku’s ip. also, try using mysqli_error() after ur query to see if there’s any specific error. don’t forget to close the connection when ur done. good luck with ur bot!

I’ve dealt with similar issues before and managed to get past them by checking a couple of things. First, ensure that your MySQL server allows remote connections from your Heroku environment. Sometimes the connection issues are due to the server not accepting external IPs. Also, verify that your credentials are correct and that there are no typos in your configuration. It’s important to implement proper error handling around your database operations so you can capture any failures. Another point is reconsidering how you send raw JSON data directly to the user—it might be better to parse and format it for clarity. With these adjustments, you should see your bot handle the database calls more reliably.