Script executes mysql query and returns column name + result

I'm scripting a little tool that I troubleshoot wordpress sites with.

This script has a function called wpsql which I pass SQL queries into. Then, it calls another function called wpdb_creds. wpdb_creds echos 5 variables parsed from wp-config.php; the database host, name, username, and password, in that order. wpsql catches these variables and stores them in a local variable as a string. the local variable is then split into an array and stored in another variable using IFS. Then i execute the query by using the mysql command, giving it the database credentials and the query. The output from this is echo'd.

However, the problem I'm having is, the script will return the column name as well as the output from the query. For example, when I execute a query such as (ignore %table_prefix%, it gets replaced with the database table prefix in wp-config.php using sed in wpsql):

SELECT option_value FROM %table_prefix%options WHERE option_name='active_plugins';

The output I get is:

option_value a:5:{i:0;s:29:"gravityforms/gravityforms.php";i:1;s:45:"no-captcha-recaptcha/no-captcha-recaptcha.php";i:2;s:25:"relevanssi/relevanssi.php";i:3;s:41:"woot-search-engine/woot-search-engine.php";i:4;s:23:"wordfence/wordfence.php";}

option_value shouldn't be returned in the output and I can't figure out why it's doing so. Here are the functions involved:

function wp_domain_root {
	found=false;local root='';cwd=${PWD} 
	IFS="/" read -a dirs <<< "$cwd"
	for((i="${#dirs[@]}"; i>0; i--)); do 
		tmp_dir=""
		for((ii=0;ii < $i; ii++)); do 
			tmp_dir+="${dirs[ $ii ]}/"
		done
	
		if [ -f $tmp_dir"/wp-config.php" ]; then root=$tmp_dir; break; fi
	done
	
	echo $root
}

function wpdb_creds {
	local domain_root=$(wp_domain_root)
	
	if [[ ${#domain_root} -ge 5 ]]; then
		read -r dbhost dbname dbpass dbuser dbprefix <<< $(cat $domain_root"wp-config.php" | egrep "^[^/].*[\"']DB_(NAME|USER|PASSWORD|HOST[^_])|table_prefix" | sort -d | sed "s/.*[\"']\(.*\)[\"'].*;.*/\1/" )
	
		if [[ ! -z $1 && $1 == '-p' ]]; then 
			echo -e "\nWP Database Info\n\tHostname: "$dbhost"\n\tDatabase: "$dbname"\n\tPassword: "$dbpass"\n\tUsername: "$dbuser"\n\tPrefix:   "$dbprefix"\n";
		else
			local dbcreds=($dbhost $dbname $dbpass $dbuser $dbprefix)
			echo "${dbcreds[@]}"
	fi; else echo -e 'Could not find a wp-config.php file...'; fi
}

function wp_sql {
	[email protected]
	local query=$(IFS=" "; echo "${args[*]}")

if [[ ! -z $1 ]]; then local dbcredstr=$(wpdb_creds)
IFS=" " read -a dbcreds <<< "$dbcredstr" if [ "${#dbcreds[@]}" -eq 5 ]; then sql_query=$(echo $query | sed "s/%table_prefix%/${dbcreds[4]}/g") echo $(mysql -u "${dbcreds[3]}" -p"${dbcreds[2]}" -h "${dbcreds[0]}" -D "${dbcreds[1]}" -e "$sql_query" 2>&1) fi fi }

function wpplug_print_active {
    echo $(wp_sql "SELECT option_value FROM %table_prefix%options WHERE option_name='active_plugins';");
}

Relevant tags