File "drop-down.php"

Full path: /home2/santhos2/public_html/bharath-coe.firstmatrix.in.net/api/helper/drop-down.php
File size: 3.25 KiB (3332 bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Back

<?php
header('Content-Type: application/json');
include '../../config/config.php'; // Adjust path if necessary

/**
 * Fetch data dynamically with error handling
 */
function fetchData($pdo, $table, $columns = '*', $conditions = [], $orderBy = '') {
    try {
        // Validate table existence
        if (!tableExists($pdo, $table)) {
            return json_encode(["success" => false, "error" => "Table '$table' does not exist."]);
        }

        // Validate columns
        if (is_array($columns)) {
            $validColumns = getTableColumns($pdo, $table);
            foreach ($columns as $col) {
                if (!in_array($col, $validColumns)) {
                    return json_encode(["success" => false, "error" => "Column '$col' does not exist in table '$table'."]);
                }
            }
            $columns = implode(', ', $columns);
        } else {
            $columns = '*'; // Default to all columns if not provided
        }

        // Build WHERE clause dynamically
        $whereClause = "";
        if (!empty($conditions)) {
            $whereParts = [];
            foreach ($conditions as $column => $value) {
                $whereParts[] = "$column = :$column";
            }
            $whereClause = "WHERE " . implode(" AND ", $whereParts);
        }

        // Construct final SQL query
        $query = "SELECT $columns FROM $table $whereClause";
        if (!empty($orderBy)) {
            $query .= " ORDER BY $orderBy";
        }

        $stmt = $pdo->prepare($query);

        // Bind values dynamically
        foreach ($conditions as $column => $value) {
            $stmt->bindValue(":$column", $value);
        }

        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return json_encode(["success" => true, "data" => $data]);
    } catch (PDOException $e) {
        error_log("Database Error: " . $e->getMessage());
        return json_encode(["success" => false, "error" => "Database error occurred."]);
    }
}

/**
 * Check if the given table exists in the database
 */
function tableExists($pdo, $table) {
    try {
        $stmt = $pdo->prepare("SHOW TABLES LIKE :table");
        $stmt->bindValue(':table', $table);
        $stmt->execute();
        return $stmt->rowCount() > 0;
    } catch (PDOException $e) {
        return false;
    }
}

/**
 * Get all columns of a table
 */
function getTableColumns($pdo, $table) {
    try {
        $stmt = $pdo->prepare("SHOW COLUMNS FROM `$table`");
        $stmt->execute();
        $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
        return $columns ?: [];
    } catch (PDOException $e) {
        return [];
    }
}

// Example usage
// $table = "tbl_client";
// $columns = ["id", "name"]; // Specify columns
// $conditions = ["status" => "active"]; // Optional WHERE conditions
// $orderBy = "name ASC"; // Optional ORDER BY

if(!isset($_GET['table']) || $_GET['table']==""){
    echo json_encode(["success" => false, "error" => "Table name required."]);
    return 0 ;
}

$table = $_GET['table'] ?? '';
$columns = isset($_GET['columns']) ? explode(',', $_GET['columns']) : ['id', 'name'];
$conditions = isset($_GET['conditions']) ? json_decode($_GET['conditions'], true) : [];
$orderBy = $_GET['orderby'] ?? '';


echo fetchData($pdo, $table, $columns, $conditions, $orderBy);
?>

PHP File Manager