static $result; // Declaring the result variable as static if(!$result) { $result = mysqli_query($conn, "SELECT * FROM users"); // Query executed only once } while($row = mysqli_fetch_assoc($result)) { // Do something with each row of data }
class Database { public static function getUsers() { static $result; // Declaring the result variable as static if(!$result) { $result = mysqli_query($this->conn, "SELECT * FROM users"); // Query executed only once } return mysqli_fetch_all($result, MYSQLI_ASSOC); } } $database = new Database(); $users = $database->getUsers(); // Retrieve data using static queryIn this example, we wrap the static query function inside a PHP class. The `getUsers()` function returns an array of data retrieved from the static query. The query is executed only once and the result is stored in the static variable `$result`. Package library: PHP MySQLi Extension (included in PHP core) PHP static query is a powerful technique to improve the performance of PHP scripts that execute the same query multiple times. It is commonly used in web applications to retrieve data from a database or perform expensive calculations. Most PHP database extensions such as MySQLi and PDO support static queries.