Insert data into database with Telegram bot


#1

I’m working to a Telegram bot and I want to insert a string, which is a string of a message, into the database, but it doesn’t work and I can’t understand why…

This is the code I’m using:

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";


$token = "TOKEN";
$website = "https://api.telegram.org/bot".$token;

$updates = file_get_contents('php://input');
$updates = json_decode($updates, TRUE);

$text = $updates['message']['text'];
$chat_id = $updates['message']['chat']['id'];

switch($text){

   //other cases...
    
    case "/test":
        $str = $updates['message']['reply_to_message']['text'];
        $insert = 'INSERT INTO test VALUES (\'\',"'.$str.'");';
        mysqli_query($conn,$insert);
        sendMessage($chat_id, $str);
        break;

//other cases...

}

//sendMessage($chat_id, $text);

function sendMessage($id, $message){
    $url = $GLOBALS[website]."/sendMessage?chat_id=".$id."&text=".urlencode($message);
    file_get_contents($url);
}

?>

I’m waiting for a response…


#2

Hi @brasco142!

Do you receive any output errors? Please go to 000webhost cPanel > Settings > General and turn error reporting on :slight_smile:


#3

Hi, I’ve checked the error reporting and it’s on.
The table of the db has this specific attributes:

Seriously I can’t understand what (and where) is the problem.


#4

We’re using MariaDB system which may be slight different from traditional MySQL. Your query should be like this:

$insert = "INSERT INTO test(stringa) VALUES ('$str');"; // assuming id is auto increment

#5

Thank you now it works!
So I have to be very strict with the syntax.


#6

Yes…

Also please do not use the Telegram outside learning purposes. BOTs of any kind are usually overloading our servers which leads to account suspension :slight_smile:


#7