You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PHP数组输出为HTML表格?课程项目技术求助

Hey Jorge, let's work through this step by step to get your Bootstrap table working, fix the logic gaps in your code, and make sure your search handles multiple criteria correctly. Here's what we'll address:

First: Fix Critical Issues in Your Original Code

Your initial PHP has a few key problems that break functionality and security:

  • Switch case missing breaks: The second and third cases don't have break, so they'll override each other even if a previous condition was met.
  • SQL Injection Risk: You're directly concatenating user input into your query—never do this! Use prepared statements instead.
  • Mismatched form field names: Your HTML uses name="Nlocal" but your PHP looks for $Blocal.
  • Broken redirects: header("url=busqueda.html") isn't valid syntax, and using Refresh will yank users away before they can see results.
  • Single-criteria only: Your switch only handles one search term at a time, but you want to support combining multiple criteria.

Step 1: Updated HTML Form with Bootstrap

Let's create a clean, single form with matching field names, add a submit button, and include Bootstrap's CDN so your styles work. Save this as search.php:

<!DOCTYPE html>
<html lang="es">
<head>
    <title>Búsqueda de Contratos</title>
    <meta charset="utf-8">
    <!-- Bootstrap CSS CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <div class="jumbotron">
            <h2 class="mb-4">Buscar Contratos</h2>
            <!-- Single form for all search criteria -->
            <form method="get" action="search.php" class="mb-4">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label for="Bcedula" class="form-label"># de Cédula</label>
                        <input type="text" class="form-control" id="Bcedula" name="Bcedula" placeholder="Ingrese cédula">
                    </div>
                    <div class="col-md-4">
                        <label for="Blocal" class="form-label">ID de Local</label>
                        <input type="text" class="form-control" id="Blocal" name="Blocal" placeholder="Ingrese ID de local">
                    </div>
                    <div class="col-md-4">
                        <label for="Bcontrato" class="form-label"># de Contrato</label>
                        <input type="text" class="form-control" id="Bcontrato" name="Bcontrato" placeholder="Ingrese número de contrato">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary mt-3">Buscar</button>
            </form>

            <!-- Results Table -->
            <?php include 'search-handler.php'; ?>
        </div>
    </div>
    <!-- Bootstrap JS (optional for interactivity) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Step 2: Secure PHP Search Handler

Create search-handler.php to handle the database query, support multiple criteria, and output the Bootstrap table. This file will be included in search.php to show results directly on the same page:

<?php
// Database connection
$con = mysqli_connect("localhost", "root", "", "estrella");
if (!$con) {
    die('Error al conectar al servidor: ' . mysqli_connect_error());
}

$min_length = 3;
$conditions = [];
$params = [];
$types = '';

// Collect valid search criteria
if (!empty($_GET['Bcedula']) && strlen($_GET['Bcedula']) >= $min_length) {
    $conditions[] = "Ncedula LIKE ?";
    $params[] = "%{$_GET['Bcedula']}%";
    $types .= 's';
}

if (!empty($_GET['Blocal']) && strlen($_GET['Blocal']) >= $min_length) {
    $conditions[] = "Nlocal LIKE ?";
    $params[] = "%{$_GET['Blocal']}%";
    $types .= 's';
}

if (!empty($_GET['Bcontrato']) && strlen($_GET['Bcontrato']) >= $min_length) {
    $conditions[] = "Ncontrato LIKE ?";
    $params[] = "%{$_GET['Bcontrato']}%";
    $types .= 's';
}

// Only run query if there are valid conditions
if (!empty($conditions)) {
    $sql = "SELECT * FROM contrato WHERE " . implode(" AND ", $conditions);
    $stmt = mysqli_prepare($con, $sql);
    
    // Bind parameters for prepared statement
    if (!empty($params)) {
        mysqli_stmt_bind_param($stmt, $types, ...$params);
    }
    
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if (mysqli_num_rows($result) > 0) {
        // Render Bootstrap table
        echo '<table class="table table-hover table-striped">';
        echo '<thead class="table-dark">';
        echo '<tr>
                <th># de Contrato</th>
                <th># de Cédula</th>
                <th>Primer Nombre</th>
                <th>Segundo Nombre</th>
                <th>Primer Apellido</th>
                <th>Segundo Apellido</th>
                <th>Local</th>
                <th>NIT</th>
                <th>Cámara de Comercio</th>
                <th>Dirección</th>
                <th>Teléfono</th>
                <th>Valor Contrato</th>
                <th>Fecha Inicio</th>
                <th>Número de Cuotas</th>
              </tr>';
        echo '</thead><tbody>';
        
        while ($row = mysqli_fetch_assoc($result)) {
            echo '<tr>';
            echo "<td>{$row['Ncontrato']}</td>";
            echo "<td>{$row['Ncedula']}</td>";
            echo "<td>{$row['Nombre1']}</td>";
            echo "<td>{$row['Nombre2']}</td>";
            echo "<td>{$row['Apellido1']}</td>";
            echo "<td>{$row['Apellido2']}</td>";
            echo "<td>{$row['Nlocal']}</td>";
            echo "<td>{$row['Nnit']}</td>";
            echo "<td>{$row['Ncamara']}</td>";
            echo "<td>{$row['Direccion']}</td>";
            echo "<td>{$row['Telefono']}</td>";
            echo "<td>{$row['Vcontrato']}</td>";
            echo "<td>{$row['Vfechainicio']}</td>";
            echo "<td>{$row['Vcuotas']}</td>";
            echo '</tr>';
        }
        
        echo '</tbody></table>';
    } else {
        echo '<div class="alert alert-warning">No se encontraron resultados para sus criterios de búsqueda.</div>';
    }

    mysqli_stmt_close($stmt);
} elseif (!empty($_GET)) {
    // If form was submitted but no valid criteria
    echo '<div class="alert alert-danger">Por favor ingrese al menos ' . $min_length . ' caracteres en al menos un campo de búsqueda.</div>';
}

mysqli_close($con);
?>

Key Improvements Explained

  • Multiple Criteria Support: Now users can search by any combination of cédula, local ID, or contrato ID—all at once if they want.
  • Security: Uses prepared statements to eliminate SQL injection risks.
  • Bootstrap Integration: The form and table use Bootstrap classes for clean, responsive styling.
  • User Feedback: Shows clear alert messages for no results or invalid input.
  • No Redirects: Results load directly on the same page so users can see them immediately.
  • Mismatched Names Fixed: Form field names now match the PHP variables.

Just replace your existing files with these two, and make sure your database credentials (host, username, password, db name) are correct in search-handler.php. This should work perfectly for your course project, and your teacher will appreciate the clean, secure implementation!

内容的提问来源于stack exchange,提问作者Jorge Andres Bitar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:53:26