K
K
konellemhs2020-01-22 06:31:21
PHP
konellemhs, 2020-01-22 06:31:21

How to get chat_id for database search?

Hello!
I’m creating a telegram bot, so far the functionality is quite simple, but not the essence)
I use a webhook, get $result, pull out the necessary data (chat_id, username, etc.)
The add_user function is used to write the user to the database if he wrote to the bot for the first time.
The get_user function, respectively, to find the user in the database.

function add_user($connect, $username, $chat_id, $name, $date, $old_id){
        $username   = trim($username);
        $chat_id    = trim($chat_id);
        $name       = trim($name);
        
      

        if($chat_id == $old_id){
            return false;
        }
        $t = "INSERT INTO users (username, user_chat_id, name, date_start) VALUES ('%s', '%s', '%s', '%s')";
        $query = sprintf($t, mysqli_real_escape_string($connect, $username),
                             mysqli_real_escape_string($connect, $chat_id),
                             mysqli_real_escape_string($connect, $name),
                             mysqli_real_escape_string($connect, $date));
        $result = mysqli_query($connect, $query);
        if(!$result){
            die(mysqli_error($connect));}
        return true;
}

function get_user($connect, $chat_id){
    
  $query = sprintf("SELECT * FROM users WHERE user_chat_id=%d", (int)$chat_id);
  $result = mysqli_query($connect, $query);
  if(!$result)
    die(mysqli_error($connect));
    $get_user = mysqli_fetch_assoc($result);
    DEBUG($get_user);
  return $get_user;

}

I ran into a problem that the record is in the database, the lines appear, but it is not possible to get the record from the database, NULL is passed to the $chat_id parameter.
User search call:
$chat_id = $result["message"]["chat"]["id"];
$get_user = get_user($connect, $chat_id);

What could be the reason and what to do about it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AUser0, 2020-01-22
@AUser0

Make sure $result["message"]["chat"]["id"] has at least something in it. And then - that this is the chat_id number, of course.

K
konellemhs, 2020-01-22
@konellemhs

It may sound strange, but perhaps there was some kind of bug (xs), now everything works, did not change anything)) When you try to do var_dump(), the array elements are not printed, as I understand it, this is due to the fact that it works through a webhook (correct , if not right), because with "long pull" it prints out perfectly. Due to the fact that it doesn’t print out via var_dump(), I thought that nothing was passed there (( My cant
However, it’s interesting to hear or read why an array is printed with a long pull, but not with a webhook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question