www
/
wwwroot
/
events.scriptexpert.net
/
includes
/
classes
➕ New
📤 Upload
✎ Editing:
database.class.php
← Back
<?php class Database { private mysqli $connection; private static ?self $instance = null; private function __construct() { $this->connection = new mysqli( DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME ); if ($this->connection->connect_error) { // dacă vrei răspuns JSON și aici, comentează throw și fă return/exit throw new Exception("Database connection failed: " . $this->connection->connect_error); } $this->connection->set_charset("utf8mb4"); } public static function getInstance(): self { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } public function getConnection(): mysqli { return $this->connection; } // ❗ Fallback – doar dacă e absolut necesar public function sanitize(string $value): string { return $this->connection->real_escape_string(trim($value)); } /** * Execută un query pregătit și întoarce mereu structură JSON-friendly. * * @param string $sql ex: "SELECT * FROM users WHERE id=?" * @param array $params ex: [1] * @param string $types ex: "i" (dacă e gol, se auto-detectează) * * @return array JSON-friendly */ public function execute(string $sql, array $params = [], string $types = ""): array { $sqlTrim = ltrim($sql); $type = strtoupper(strtok($sqlTrim, " \t\n\r")); try { $stmt = $this->connection->prepare($sql); if (!$stmt) { return $this->errorResult("Prepare failed: ".$this->connection->error); } // Bind parametri dacă există if (!empty($params)) { if ($types === "") { $types = $this->detectTypes($params); } if (!$stmt->bind_param($types, ...$params)) { $msg = $stmt->error ?: $this->connection->error; return $this->errorResult("Bind failed: ".$msg); } } if (!$stmt->execute()) { $msg = $stmt->error ?: $this->connection->error; return $this->errorResult("Execute failed: ".$msg); } // Răspunsuri în funcție de tip if ($type === 'SELECT' || $type === 'SHOW' || $type === 'DESCRIBE' || $type === 'EXPLAIN') { $data = []; if (method_exists($stmt, 'get_result')) { $result = $stmt->get_result(); if ($result === false) { $msg = $stmt->error ?: $this->connection->error; $stmt->close(); return $this->errorResult("get_result failed: ".$msg); } $data = $result->fetch_all(MYSQLI_ASSOC) ?: []; } else { // Fallback fără mysqlnd: mapăm manual rezultatele $meta = $stmt->result_metadata(); if ($meta) { $fields = []; $row = []; while ($field = $meta->fetch_field()) { $fields[] = &$row[$field->name]; } call_user_func_array([$stmt, 'bind_result'], $fields); while ($stmt->fetch()) { $data[] = array_map(fn($v) => $v, $row); } $meta->free_result(); } } $rows = is_array($data) ? count($data) : 0; $stmt->close(); return [ 'status' => 1, 'error' => 0, 'type' => 'select', 'rows' => $rows, 'data' => $data ]; } if ($type === 'INSERT' || $type === 'REPLACE') { // insert_id poate fi pe stmt (PHP 8.1+) sau pe connection $insertId = property_exists($stmt, 'insert_id') ? $stmt->insert_id : $this->connection->insert_id; $affected = $stmt->affected_rows; $stmt->close(); return [ 'status' => 1, 'error' => 0, 'type' => strtolower($type) === 'replace' ? 'replace' : 'insert', 'insert_id' => (int)$insertId, 'affected_rows' => (int)$affected ]; } if ($type === 'UPDATE' || $type === 'DELETE') { $affected = $stmt->affected_rows; $stmt->close(); return [ 'status' => 1, 'error' => 0, 'type' => strtolower($type), 'affected_rows' => (int)$affected ]; } // Alte comenzi (DDL etc.) $affected = $stmt->affected_rows; $stmt->close(); return [ 'status' => 1, 'error' => 0, 'type' => strtolower($type), 'affected_rows' => (int)$affected ]; } catch (Throwable $e) { return $this->errorResult($e->getMessage()); } } private function detectTypes(array $params): string { $types = ""; foreach ($params as $param) { if (is_int($param)) { $types .= "i"; } elseif (is_float($param)){ $types .= "d"; } elseif (is_null($param)) { $types .= "s"; /* trimitem ca string */ } else { $types .= "s"; } } return $types; } private function errorResult(string $message): array { // încercăm să expunem și contextul MySQL (dacă există) $sqlstate = $this->connection->sqlstate ?? null; $errno = $this->connection->errno ?? null; return [ 'status' => 0, 'error' => 1, 'message' => $message, 'sqlstate'=> $sqlstate, 'errno' => $errno ]; } public function close(): void { if ($this->connection) { $this->connection->close(); } } } // Singleton global (dacă vrei) $database = Database::getInstance(); /* ** INSERT ** $userId = $database->execute( "INSERT INTO users (username, email, password) VALUES (?, ?, ?)", ["george", "george@example.com", password_hash("secret", PASSWORD_BCRYPT)] ); echo "User creat cu ID: " . $userId; ** UPDATE ** $rows = $database->execute( "UPDATE users SET email=? WHERE id=?", ["george.new@example.com", 1] ); echo "Rânduri modificate: " . $rows; ** SELECT ** $users = $database->execute( "SELECT id, username, email FROM users WHERE email LIKE ?", ["%@example.com%"] ); print_r($users); ** SELECT SINGLE ROW ** $user = $database->execute( "SELECT id, username, email FROM users WHERE id=?", [1] ); if (!empty($user)) { print_r($user[0]); // primul rând } ** DELETE ** $deleted = $database->execute( "DELETE FROM users WHERE id=?", [2] ); echo "Rânduri șterse: " . $deleted; */
💾 Save Changes
Cancel
📤 Upload File
×
Select File
Upload
Cancel
➕ Create New
×
Type
📄 File
📁 Folder
Name
Create
Cancel
✎ Rename Item
×
Current Name
New Name
Rename
Cancel
🔐 Change Permissions
×
Target File
Permission (e.g., 0755, 0644)
0755
0644
0777
Apply
Cancel