48: Replace Deprecated MySQLi Charset and Statement Calls
Overview
Section titled “Overview”Check the connection charset and run a bound query without creating an empty statement. PHP 8.6 deprecates get_charset(), stmt_init(), their procedural counterparts and constructing mysqli_stmt without SQL.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
mysqliextension and a reachable local MySQL or MariaDB server. SetMYSQL_USERfor an account with permission to connect. Optionally setMYSQL_HOST(default127.0.0.1),MYSQL_PORT(default3306), andMYSQL_PASSWORDfor that account. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable mysqli-charset-and-statements.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/48-mysqli-charset-and-statements/mysqli-charset-and-statements.php<?php
declare(strict_types=1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);$db = new mysqli( getenv('MYSQL_HOST') ?: '127.0.0.1', getenv('MYSQL_USER') ?: 'root', getenv('MYSQL_PASSWORD') ?: '', port: (int) (getenv('MYSQL_PORT') ?: '3306'),);try { $db->set_charset('utf8mb4'); echo $db->character_set_name(), PHP_EOL; $result = $db->execute_query('SELECT ? AS message', ["Today's specials"]); echo $result->fetch_assoc()['message'], PHP_EOL;} finally { $db->close();}Expected Result
Section titled “Expected Result”utf8mb4Today's specialsWhy It Works
Section titled “Why It Works”Use character_set_name() when the application needs the current charset name. It returns a string, so audit consumers that used other fields on the former object. Prepare SQL with prepare() or use execute_query() to prepare, bind and execute in one call.
Exercise
Section titled “Exercise”Add a second placeholder for a number. Pass it as the second bound value and select both columns to verify the order.
Wrap-up
Section titled “Wrap-up”Continue with Migrate SplFileObject CSV Calls.