diff --git a/sys/sys.php b/sys/sys.php index 97c0461..dd880fc 100755 --- a/sys/sys.php +++ b/sys/sys.php @@ -5,23 +5,55 @@ * * */ -function sql_read($query) { +prepare($query); - if ($stmt->execute() === false) return ["status" => "error", "query"=>$query]; - return $stmt->fetchAll(PDO::FETCH_ASSOC); + + // If custom credentials are provided, create a fresh, temporary connection + // This prevents overwriting the global $db with an alternative database + if ($db_host !== null || $db_user !== null || $db_pass !== null) { + $host = $db_host ?? DB_HOST; + $user = $db_user ?? DB_USER; + $pass = $db_pass ?? DB_PASS; + return new PDO("mysql:host=" . $host . ";", $user, $pass); + } + + // Otherwise, use or initialize the global connection using constants + if (!isset($db) || is_null($db)) { + $db = new PDO("mysql:host=" . DB_HOST . ";", DB_USER, DB_PASS); + } + return $db; } -function sql_write($query) { - global $db; - if (!isset($db) || is_null($db)) $db = new PDO("mysql:host=".DB_HOST.";",DB_USER,DB_PASS); - $stmt = $db->prepare($query); - if ($stmt->execute() === false) die ("sql error: $query"); - return $stmt->rowCount(); + +function sql_read($query, $db_host = null, $db_user = null, $db_pass = null) { + $pdo = get_db_connection($db_host, $db_user, $db_pass); + $stmt = $pdo->prepare($query); + + if ($stmt->execute() === false) { + return ["status" => "error", "query" => $query]; + } + return $stmt->fetchAll(PDO::FETCH_ASSOC); } -function sql($query) { - if (strpos($query, "SELECT ") === 0) return sql_read($query); - else return sql_write($query); + +function sql_write($query, $db_host = null, $db_user = null, $db_pass = null) { + $pdo = get_db_connection($db_host, $db_user, $db_pass); + $stmt = $pdo->prepare($query); + + if ($stmt->execute() === false) { + die("sql error: $query"); + } + return $stmt->rowCount(); +} + +function sql($query, $db_host = null, $db_user = null, $db_pass = null) { + // Used trim() and stripos() to catch cases like " select " or "SELECT " + if (stripos(trim($query), "SELECT") === 0) { + return sql_read($query, $db_host, $db_user, $db_pass); + } else { + return sql_write($query, $db_host, $db_user, $db_pass); + } }