Prepared statements in PHP
Non-review answers


what security threats this script can prevent - sql injection 
what security threats this script is vulnerable to - sql injection
how these threats are blocked - https://stackoverflow.com/questions/8263371/how-can-prepared-statements-protect-from-sql-injection-attacks


Review answer.

Your code is bloated with unnecessary operators, such as heredoc. 
It is also recommended to use PDO instead of sqlite, as it will let you to use array binding, which is especially useful in this case as you are inserting equal sets of data.

Besides, you should use prepared statements for your database interactions.

There are also other improvements and fixes.

if (!empty($_POST['userMsgField']) &amp;&amp; !empty($_POST['hash']))
{
    $my_id = $_SESSION['log_id'];
    $rep_msg = $_POST['userMsgField'];
    $hash = $_POST['hash'];
    $flag = 0;

    $sql = "SELECT * FROM connect WHERE (user_one = ? AND hash = ?) 
                                     OR (user_two = ? AND hash = ?)";
    $stmt = $db-&gt;prepare($sql);
    $stmt-&gt;execute([$my_id,$hash,$my_id,$hash]);

    while ($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC))
    {
        $user_one = $row['user_one'];
        $user_two = $row['user_two'];

        $to_id = ($user_one == $my_id) ? $user_two : $user_one;

        $data = [
            'message' =&gt; $rep_msg,
            'group_hash' =&gt; $hash,
            'from_id' =&gt; $my_id,
            'flag' =&gt; $flag,
            'to_id' =&gt; $to_id,
        ];

        $sql ="INSERT INTO messager (message, group_hash, from_id, flag, to_id) 
                            VALUES (:message,:group_hash,:from_id,:flag,:to_id)";
        $db-&gt;prepare($sql)-&gt;execute($data);

        $sql ="INSERT INTO chatportal (message, group_hash, from_id, flag, to_id)
                              VALUES (:message,:group_hash,:from_id,:flag,:to_id)";
        $db-&gt;prepare($sql)-&gt;execute($data);
    }
}


Now this code is much cleaner and easier to read. And safe, of course.