@@ -1959,6 +1959,51 @@ private static function get_create_query() {
19591959 return $ create_query ;
19601960 }
19611961
1962+ /**
1963+ * Run a single query via PHP's mysqli extension.
1964+ *
1965+ * Used as a fallback when the MySQL/MariaDB binary is not available.
1966+ * Creates a fresh connection per call so that DDL operations like
1967+ * DROP DATABASE followed by CREATE DATABASE work correctly.
1968+ *
1969+ * @param string $query SQL query to execute.
1970+ */
1971+ protected function run_query_via_mysqli ( $ query ) {
1972+ $ db_host = DB_HOST ;
1973+ $ port = null ;
1974+ $ socket = null ;
1975+
1976+ if ( ': ' === substr ( $ db_host , 0 , 1 ) ) {
1977+ $ socket = substr ( $ db_host , 1 );
1978+ $ db_host = 'localhost ' ;
1979+ } else {
1980+ $ parts = explode ( ': ' , $ db_host , 2 );
1981+ $ db_host = $ parts [0 ];
1982+ if ( isset ( $ parts [1 ] ) ) {
1983+ $ port_or_socket = trim ( $ parts [1 ] );
1984+ if ( '/ ' === $ port_or_socket [0 ] ) {
1985+ $ socket = $ port_or_socket ;
1986+ } else {
1987+ $ port = (int ) $ port_or_socket ;
1988+ }
1989+ }
1990+ }
1991+
1992+ // phpcs:ignore WordPress.DB.RestrictedClasses.mysql__mysqli -- direct mysqli required as wpdb fallback when mysql binary is unavailable.
1993+ $ conn = new mysqli ( $ db_host , DB_USER , DB_PASSWORD , '' , null !== $ port ? $ port : 3306 , null !== $ socket ? $ socket : '' );
1994+
1995+ if ( $ conn ->connect_errno ) {
1996+ WP_CLI ::error ( sprintf ( 'Failed to connect to the database: %s ' , $ conn ->connect_error ) );
1997+ }
1998+
1999+ if ( ! $ conn ->query ( $ query ) ) {
2000+ $ error = $ conn ->error ;
2001+ $ conn ->close ();
2002+ WP_CLI ::error ( sprintf ( 'Query failed: %s ' , $ error ) );
2003+ }
2004+ $ conn ->close ();
2005+ }
2006+
19622007 /**
19632008 * Run a single query via the 'mysql' binary.
19642009 *
@@ -1970,20 +2015,8 @@ private static function get_create_query() {
19702015 */
19712016 protected function run_query ( $ query , $ assoc_args = [] ) {
19722017 if ( ! $ this ->is_mysql_binary_available () ) {
1973- WP_CLI ::debug ( "Query via wpdb: {$ query }" , 'db ' );
1974- $ this ->maybe_load_wpdb ();
1975- global $ wpdb ;
1976-
1977- if ( ! isset ( $ wpdb ) ) {
1978- WP_CLI ::error ( 'WordPress database (wpdb) is not available. Please install MySQL or MariaDB client tools. ' );
1979- }
1980-
1981- // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1982- $ result = $ wpdb ->query ( $ query );
1983- if ( false === $ result ) {
1984- // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags
1985- WP_CLI ::error ( 'Query failed: ' . strip_tags ( $ wpdb ->last_error ) );
1986- }
2018+ WP_CLI ::debug ( "Query via mysqli: {$ query }" , 'db ' );
2019+ $ this ->run_query_via_mysqli ( $ query );
19872020 return ;
19882021 }
19892022
0 commit comments