I’m working on a Telegram bot that creates a keyboard from database records. I need help adding extra buttons to the keyboard that come from the database.
Here’s my current setup:
$song_query = mysqli_query($connection, "SELECT * FROM audio_tracks");
if(mysqli_num_rows($song_query) > 0){
while($track_data = mysqli_fetch_assoc($song_query)) {
$buttons[][] = $track_data['song_name'];
}
var_dump(
sendTelegramRequest('sendMessage',[
'chat_id' => $user_id,
'text' => "Pick a song from the list.",
'reply_markup' => json_encode(array('keyboard' => $buttons))
])
);
}
This gives me a keyboard with database items like:
$buttons = [['Song A'], ['Song B']];
But I want to add my own buttons to this array. How can I include additional custom buttons alongside the database results? I’m trying to get something like:
just add your custom buttons after the while loop. drop in $buttons[][] = 'Go Back'; and $buttons[][] = 'Main Menu'; right before sending the message. that’s it - should work with what you’ve already got.
You can initialize your buttons array with the custom buttons first, then add the database results. Try $buttons = [['Go Back'], ['Main Menu']]; before your while loop. Your static buttons will show up at the top instead of the bottom. This works better for navigation buttons since users expect them in the same spot every time. If you want them at the end, use array_push($buttons, ['Go Back'], ['Main Menu']) after the loop. Just remember your button handling needs to work with both database items and static buttons when processing responses.
Had the exact same problem with my music bot! You’re creating nested arrays when you don’t need to. Change $buttons[][] = $track_data['song_name']; to $buttons[] = [$track_data['song_name']]; - keeps everything consistent.
Then merge arrays like this: $custom_buttons = [['Go Back'], ['Main Menu']]; $final_buttons = array_merge($buttons, $custom_buttons); - worked perfectly for me.
One more thing - if you’ve got tons of songs, group them per row or users will hate scrolling through 50+ buttons. Try $buttons[] = [$song1, $song2, $song3]; depending on how long your song names are.