'Why does Shell Script to create database via mysql work in terminal but not with exec, passthru, or shell_exec?

I have the following basic shell script here:

#!/usr/bin/env bash

# run as root
if [ "`id -u`" -ne 0 ]; then
 exec sudo "$0" "$@"
 exit 99
fi

# dbname mandatory
if [ -z ${1+x} ]; then
  exit 1;
fi

set -a
source /path/to/vars.env

dbhost=${dbhost:=localhost}

dbname="$1"

mysql --defaults-extra-file=$dbcnf_path<<EOF
CREATE DATABASE IF NOT EXISTS $dbname;
GRANT ALL PRIVILEGES ON $dbname.* TO '$dbuser'@'$dbhost';
ALTER DATABASE $dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
EOF

echo "Database $dbname was processed."

I have a vars.env file that just sets the dbcnf_path (full directory path to a config.cnf file), dbuser, and dbhost variable values.

The config.cnf file looks like this:

[client]
user = "user"
password = "mypassword"
host = "localhost"

I have edited /etc/sudoers file to allow this .sh file to even run as root (in case that is a problem, which shouldn't be I don't think cause it just accessing mysql).

The php code that executes this (I have tried all ways: passthru, shell_exec, and finally exec none of them create the database) is as follows:

<?php 
    $dbName = 'dbNameTest';
    $cmd = './mysql_test.sh ' . $dbName;
    $data = exec($cmd, $output);
?>

Not sure why the database will not be created. Any ideas how this might need to be changed in order to work via php with exec, shell_exec, or even passthru? I'm not sure why it's not working, seems a bit odd unless that was intentional to not allow apache to update the database via php in a shell script. I've just recently updated bash to the newest version and mysql is running version 8.x.x if that helps.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source