Adapt .PHP file to .HTML to embed Javascript

-1

<?php
// Establecer conexión

session_start();
require_once "conexion_root.php";
?>
<?
// Ejecución de consulta SQL con INNER JOIN
 
$sql = "SELECT * FROM equipos"; 

if($result = $db_conn-><?query($sql)){
if($result-><?num_rows ><? 0){
?>
<html>
<head>
<meta charset="UTF-8">
<title>Inventario de Equipos</title>
<link href="./roundedcorners2.css" rel="stylesheet" type="text/css" />
<link href="./result.css" rel="stylesheet" type="text/css" />
</head>
	<body> 			
		<p align="center"><a href="inventario.html"><img src="img\att_logo.png" width="150px"/></a></p>
		<p><h1 align="center" style="font-family: calibri">Inventario de Equipos</h1></p><br>
		
		<p><input id="buscar" type="text" class="form-control" placeholder="Escriba algo para filtrar" /></p>

			<table id="tabla" class="roundedCorners2">				
				<thead>			
				<tr>
					<th>Tipo de Equipo:</th>
					<th>Número de Serie:</th>					
					<th>Marca:</th>
					<th>Modelo:</th>					
					<th>Unidades:</th>					
					<th>Proyecto:</th>					
					<th>Coordenadas del Rack:</th>					
					<th>Unidad_Inicial:</th>					
					<th>Unidad_Final:</th>					
					<th>Estado:</th>					
					<th>Situación:</th>					
					<th>Stack/Cluster:</th>					
					<th>Hostname:</th>					
					<th>IP Admin:</th>					
					<th>IOS:</th>					
					<th>Activo Fijo:</th>									
					<th>Notas: </th>					
			    </tr>

  
       <? while($row = $result-><?fetch_array())<?{?>

				<tbody>			
				<tr>
					<td><? . $row['tipo_equipo'] . ?></td>
					<td><? . $row['no_serie'] . ?></td>					
					<td><? . $row['marca'] . ?></td>
					<td><? . $row['modelo'] . ?></td>			
					<td><? . $row['unidades'] . ?></td>					
					<td><? . $row['proyecto'] . ?></td>
					<td><? . $row['coordenadas_rack'] . ?></td>
					<td><? . $row['unidad_inicial'] . ?></td>
					<td><? . $row['unidad_final'] . ?></td>				
					<td><? . $row['estado'] . ?></td>
					<td><? . $row['situacion'] . ?></td>			
					<td><? . $row['stack_cluster'] . ?></td>
					<td><? . $row['hostname'] . ?></td>
					<td><? . $row['ip_admin'] . ?></td>					
					<td><? . $row['ios'] . ?></td>				
					<td><? . $row['activo_fijo'] . ?></td>						
					<td><? . $row['notas'] . ?></td>								
				</tr>		
				</tbody>				
			<? } ?>

			</table><br>	
						
	<div>	
		<table id="resultados" class="result">
			<tr>
				<td>	
				<?
					// Determinar el número de filas del resultado 
					$row_cnt = $result-><?num_rows;	
					
					<?printf("%d resultado(s) encontrado(s).\n", ?><?$row_cnt); 
				</td>				
			</tr>
		</table>
	</div>	
	</body>
</html>
<?
// Consulta libre de resultados
$result->free();
} else{
	echo 'No se encontró ningún resultado para esta consulta.<br><br>';
	echo '<a href="http://localhost/proyecto/insert_equipos.html">Dar de alta un equipo<br><br></a>';
}

} else{
    echo 'ERROR: No fue posible ejecutar la orden $sql. [' . $db_conn->errno . "] "
            . $db_conn->error;
}

// Cerrar conexión
$db_conn->close();
?>

Dear, these trying to adapt the following PHP code in HTML to be able to insert a Javascript scrip. I hope some of you can help me a bit.

<html>
<?php    
// Establecer conexión

session_start();
require_once "conexion_root.php";

// Ejecución de consulta SQL

$sql = "SELECT * FROM equipos"; 

if($result = $db_conn->query($sql)){ 

    if($result->num_rows > 0){

        echo '<link href="./roundedcorners2.css" rel="stylesheet" type="text/css" />';      
        echo '<link href="./result.css" rel="stylesheet" type="text/css" />';

        echo '<p align="center"><a href="inventario.html"><img src="img\att_logo.png" width="150px"/></a></p>';
        echo '<p><h1 align="center" style="font-family: calibri">Inventario de Equipos</h1></p><br>';

        echo '<p><input id="buscar" type="text" class="form-control" placeholder="Escriba algo para filtrar" /></p>';

            echo '<table id="tabla" class="roundedCorners2">';              
                echo '<thead>';         
                echo '<tr>';
                    echo '<th>Tipo de Equipo:</th>';
                    echo '<th>Número de Serie:</th>';                   
                    echo '<th>Marca:</th>';
                    echo '<th>Modelo:</th>';                    
                    echo '<th>Unidades:</th>';                  
                    echo '<th>Proyecto:</th>';                  
                    echo '<th>Coordenadas del Rack:</th>';                  
                    echo '<th>Unidad_Inicial:</th>';                    
                    echo '<th>Unidad_Final:</th>';                  
                    echo '<th>Estado:</th>';                    
                    echo '<th>Situación:</th>';                 
                    echo '<th>Stack/Cluster:</th>';                 
                    echo '<th>Hostname:</th>';                  
                    echo '<th>IP Admin:</th>';                  
                    echo '<th>IOS:</th>';                   
                    echo '<th>Activo Fijo:</th>';                                   
                    echo '<th>Notas: </th>';                    
                echo '</tr>';

        while($row = $result->fetch_array()){

                echo '<tbody>';         
                echo '<tr>';
                    echo '<td>' . $row['tipo_equipo'] . '</td>';
                    echo '<td>' . $row['no_serie'] . '</td>';                   
                    echo '<td>' . $row['marca'] . '</td>';
                    echo '<td>' . $row['modelo'] . '</td>';             
                    echo '<td>' . $row['unidades'] . '</td>';                   
                    echo '<td>' . $row['proyecto'] . '</td>';
                    echo '<td>' . $row['coordenadas_rack'] . '</td>';
                    echo '<td>' . $row['unidad_inicial'] . '</td>';
                    echo '<td>' . $row['unidad_final'] . '</td>';                   
                    echo '<td>' . $row['estado'] . '</td>';
                    echo '<td>' . $row['situacion'] . '</td>';                  
                    echo '<td>' . $row['stack_cluster'] . '</td>';
                    echo '<td>' . $row['hostname'] . '</td>';
                    echo '<td>' . $row['ip_admin'] . '</td>';                   
                    echo '<td>' . $row['ios'] . '</td>';                    
                    echo '<td>' . $row['activo_fijo'] . '</td>';                            
                    echo '<td>' . $row['notas'] . '</td>';                                      
                echo '</tr>';           
                echo'</tbody>';             
            }

            echo '</table><br>';    

    echo '<div>';   
        echo '<table id="resultados" class="result">';  
            echo '<tr>';    
                echo '<td>';    

                    // Determinar el número de filas del resultado 
                    $row_cnt = $result->num_rows;   

                    printf("%d resultado(s) encontrado(s).\n", $row_cnt);  

                echo '</td>';               
            echo '</tr>';   
        echo '</table>';    
    echo '</div>';

// Consulta libre de resultados
$result->free();
} else{
    echo 'No se encontró ningún resultado para esta consulta.<br><br>';
    echo '<a href="http://localhost/proyecto/insert_equipos.html">Dar de alta un equipo<br><br></a>';
}

} else{
    echo 'ERROR: No fue posible ejecutar la orden $sql. [' . $db_conn->errno . "] "
            . $db_conn->error;
}

// Cerrar conexión
$db_conn->close();
?>
</html>
    
asked by Antonio Ortiz 21.12.2017 в 21:27
source

1 answer

1

Your question is somewhat confusing and does not make it clear what you want, but I still venture to answer two things:

  • Try to always program in layers, an HTML and CSS layer (with bootstrap, for example), another with javascript (jQuery or whatever you want) and another with PHP that links to the data. In this way it is very easy to change the whole PHP part without having to change the web for example. This would be like this (in a very simple example):
  • First we define the structure of the index.html page:

    <!doctype html>
    <html lang="en">
        <head>
            <title>Hello, world!</title>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
            <link href="micss.css" rel="stylesheet">
        </head>
        <body>
            <div class="contenedor"></div>
            <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
            <script src="micodigo.js"></script>
        </body>
    </html>
    

    Now we apply a design to micss.css:

    * {
        margin: 0px;
    }
    

    And now we load the data from micodigo.js by means of AJAX calls to the php:

    $(function() {
        $.ajax({
            method: "POST",
            url: "datos.php",
            dataType: "json",
            cache: false,
            data: {
                action: 1
            }
        }).done(function(json) {
            switch(json.statuscode) {
                case 1:
                    $(".contenedor").append(json.datos);
                    break;
            }
        });
    });
    

    Finally, we extract the data to show in the container from datos.php:

    <?php
        $return = array();
        $return["statuscode"] = 0; // Por defecto no hay error
    
        if(isset($_POST["action"])) {
            $action = sprintf("%d", $_POST["action"]);
        }
    
        switch($action) {
            case 1:
                $return["datos"] = "Hola mundo";
                break;
        }
    
        header('Content-type: application/json; charset=utf-8');
        echo json_encode($return);
        exit();
    ?>
    

    It's a very simple example, but it helps you to have things separate so you can easily modify them.

  • You can simply execute the code and save the resulting page from the browser, with this you have the generated and clean HTML to which you can add the javascriprt.
  • Finally tell you that there is no problem in directly adding the javascript code in the PHP itself. For example:

    echo '<td onclick="javascript: mifuncion();">' . $row['tipo_equipo'] . '</td>';
    

    Or you can add other things:

    echo "<script>";
    echo "alert('hola mundo');";
    echo "</script>";
    

    And the result is that on the client side, you'll see the javascript alert generated from PHP without problems.

        
    answered by 16.01.2018 в 15:42