wpdb::get_table_from_query()protectedWP 4.2.0

Finds the first table name referenced in a query.

Method of the class: wpdb{}

No Hooks.

Return

String|false. The table name found, or false if a table couldn't be found.

Usage

// protected - for code of main (parent) or child class
$result = $this->get_table_from_query( $query );
$query(string) (required)
The query to search.

Changelog

Since 4.2.0 Introduced.

wpdb::get_table_from_query() code WP 6.5.2

protected function get_table_from_query( $query ) {
	// Remove characters that can legally trail the table name.
	$query = rtrim( $query, ';/-#' );

	// Allow (select...) union [...] style queries. Use the first query's table name.
	$query = ltrim( $query, "\r\n\t (" );

	// Strip everything between parentheses except nested selects.
	$query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );

	// Quickly match most common queries.
	if ( preg_match(
		'/^\s*(?:'
			. 'SELECT.*?\s+FROM'
			. '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
			. '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
			. '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
			. '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:.+?FROM)?'
		. ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is',
		$query,
		$maybe
	) ) {
		return str_replace( '`', '', $maybe[1] );
	}

	// SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'wp_posts'
	if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES).+WHERE\s+Name\s*=\s*("|\')((?:[0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)\\1/is', $query, $maybe ) ) {
		return $maybe[2];
	}

	/*
	 * SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%'
	 * This quoted LIKE operand seldom holds a full table name.
	 * It is usually a pattern for matching a prefix so we just
	 * strip the trailing % and unescape the _ to get 'wp_123_'
	 * which drop-ins can use for routing these SQL statements.
	 */
	if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES)\s+(?:WHERE\s+Name\s+)?LIKE\s*("|\')((?:[\\\\0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)%?\\1/is', $query, $maybe ) ) {
		return str_replace( '\\_', '_', $maybe[2] );
	}

	// Big pattern for the rest of the table-related queries.
	if ( preg_match(
		'/^\s*(?:'
			. '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
			. '|DESCRIBE|DESC|EXPLAIN|HANDLER'
			. '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
			. '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
			. '|TRUNCATE(?:\s+TABLE)?'
			. '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
			. '|ALTER(?:\s+IGNORE)?\s+TABLE'
			. '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
			. '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
			. '|DROP\s+INDEX.*\s+ON'
			. '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
			. '|(?:GRANT|REVOKE).*ON\s+TABLE'
			. '|SHOW\s+(?:.*FROM|.*TABLE)'
		. ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is',
		$query,
		$maybe
	) ) {
		return str_replace( '`', '', $maybe[1] );
	}

	return false;
}