@isaiah, that makes sense.
I’ll start with some more context.
Here is my SQL table:
It has an ID, Command, Responce, and Function for each row .
Here is what the function looks like to define a command and response for a BotMan chatbot:
$botman->hears('Can you hear me', function ($bot) {
$bot->reply('You are coming in loud and clear');
});
Rather than code one of these functions for each command/response, I would like to automatically generate the function for each row in the table.
I start by connecting to the SQL database and querying the commands_general table.
<?php
//Define Variables for connecting to MySQL Database
$servername = "localhost";
$username = "USR";
$password = "PASS";
$dbname = "DB_NAME";
// Create a connection to MySQL database with commands and responses
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Define which data to retrieve and from which table in the database
$sql = "SELECT id, command, responce FROM commands_general";
//Get the results from the query in $sql
$result = $conn->query($sql);
Now it’s time to create a command and response from each row in the commands_general table.
//If there is at least one row in the results then continue
if ($result->num_rows > 0) {
//Set a global variable $counter that will be used to pass the correct response into the $botman->hears function
$GLOBALS['counter'] = 0;
//Loop through each Row in the results
while($row = $result->fetch_assoc()) {
//Create a variable for each row based on the ID for that row in the table
$responceId = 'responce'.$row["id"];
//This will create $responce1, $responce2, $responce3 and assign the 'responce' associated with the row/ID ($responce1 = 'Hello Brandon', $responce2 = 'it works', $responce3 = 'you rock')
$GLOBALS[$responceId] = $row['responce'];
//Here is where thisngs get ticky due to variable scopes
$botman->hears($row['command'], function ($bot) {
//Pull in the $counter variable from outside of this function
static $counter;
//Create a variable name using the $counter variable which should result in a variable that corrisponds with a command/responce from the table
$response = 'reponce'.$counter;
global $$response;
//Set the reply to be the value of the variable name generated by $responce (i.e. responce1, responce2, responce3)
$bot->reply($$response);
});
// Add 1 to the $counter variable each loop.
$GLOBALS['counter']++;
}
}
//Close the SQL Connection
$conn->close();
The issue that I am having now is that when I put $GLOBALS[‘counter’] inside the $botman->hears function It always equals ‘3’. This means that every command responds with $responce3 = ‘you rock’.
So rather than adding 1 to the counter, then creating the $botman->hears function, then adding 1 to the counter and repeating, I am adding 1 to the counter for each row and then passing the final count to the $botman->hears function.