I use the following code to establish a connection with the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mysb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>
Then I try to execute this statement from another PHP page and it works only if an update statement gets coded before another select statement:
<?php
  require_once (getcwd()."connection.php");    
  function callme(){
    if (isset($_GET['check'])) {
      $ip = $_SERVER['REMOTE_ADDR'];
      $sql = "UPDATE Table SET IpAddress = ? WHERE Key = ?";
      $stmt = $GLOBALS['conn']->prepare($sql);
      //if (!$stmt)
        //die("Error occurred");
      $stmt->bind_param("ss", $ip,$g);
      $stmt->execute();
    }
  }
    
  if (isset($_GET['g']) && !empty($_GET['g'])){
    $g = $_GET['g'];
    callme(); //called before the select statement below
    $sql = "SELECT T FROM Table WHERE Key = ?";
    $stmt = $GLOBALS['conn']->prepare($sql);
    //if (!$stmt)
      //die("Error occurred");
    $stmt->bind_param("s", $g);
    $stmt->execute();
    $stmt->bind_result($result);
    $stmt->fetch();
   }
?>
This works correctly. p.s: all queries are correct and already tested manually.
The strange thing is that if I try to call the callme() function after the select statement like this:
<?php
  require_once (getcwd()."connection.php");    
  function callme(){
    if (isset($_GET['check'])) {
      $ip = $_SERVER['REMOTE_ADDR'];
      $sql = "UPDATE Table SET IpAddress = ? WHERE Key = ?";
      $stmt = $GLOBALS['conn']->prepare($sql);
      //if (!$stmt)
        //die("Error occurred");
      $stmt->bind_param("ss", $ip,$g);
      $stmt->execute();
    }
  }
    
  if (isset($_GET['g']) && !empty($_GET['g'])){
    $g = $_GET['g'];
  
    $sql = "SELECT T FROM Table WHERE Key = ?";
    $stmt = $GLOBALS['conn']->prepare($sql);
    //if (!$stmt)
      //die("Error occurred");
    $stmt->bind_param("s", $g);
    $stmt->execute();
    $stmt->bind_result($result);
    $stmt->fetch();
    callme();//called after the select statement above
   }
?>
I get the following error: Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in /Users/user/Sites/test.php:13 Stack trace: #0 /Users/user/Sites/test.php(32): callme() #1 {main} thrown in /Users/user/Sites/test.php on line 12
where the line 12 is exactly $stmt->bind_param("ss", $ip,$g);.
What am I missing here?
Solved:
For those who are trying to resolve this problem just add a:
$stmt->free_result();
after your statements. The question already answered and proposed as duplicated is a little bit off-topic. Check out for PHP Commands Out of Sync error and https://dba.stackexchange.com/questions/130019/commands-out-of-sync-you-cant-run-this-command-now for better understandings.
