Featured Post

Tablas Responsivas con Bootstrap 5 pc escritorio y dispositivos mobiles

CARGAR TABLA ARTICULOS ARRAY json_encode METODO GET JQUEY PHP MYSQL




 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<style>

body {
font-family: Verdana;
}


table, td, th {  
  border: 1px solid #ddd;
  text-align: left;
}

table {
  border-collapse: collapse;
  width: 100%;
}

th, td {
  padding: 15px;
}
</style>


<?php

/*
// Conectarse a la base de datos
$conexion = new mysqli("localhost", "root", "root", "tienda");

// Obtener los datos de la tabla de artículos
$resultados = $conexion->query("SELECT * FROM articulos");

// Cerrar la conexión a la base de datos
$conexion->close();

// Convertir los resultados a un array asociativo
$articulos = array();
while ($fila = $resultados->fetch_assoc()) {
  $articulos[] = $fila;
}

*/


// Conectarse a la base de datos
$conexion = new PDO("mysql:host=localhost;dbname=tienda", "root", "root");
$conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Preparar la consulta
$consulta = $conexion->prepare("SELECT * FROM articulos");

// Ejecutar la consulta
$consulta->execute();

// Obtener los resultados
$articulos = $consulta->fetchAll();


//echo $articulos[0]["nombre"];
//echo "<br>";
//echo "<hr>";
//echo "<br>";
//echo "<br>";


//$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($articulos);

for($i = 0; $i < $arrlength; $i++) {
  echo $articulos[$i]["nombre"]." _ $".$articulos[$i]["precio"];
  echo "<hr>";
}


// Cerrar la conexión
//$conexion = null;

echo "<br>";
echo "<br>";

?>

</head>


<body>
<table id="articulos">
  <thead>
    <tr>
      <th>ID</th>
      <th>Nombre</th>
      <th>Precios</th>
      <th>foto</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>


<script>
$(document).ready(function() {

  // Obtener los datos de la tabla de artículos de PHP
  var datos = <?php echo json_encode($articulos); ?>;

  // Vaciar la tabla HTML
  $("#articulos tbody").empty();

  // Recorrer los datos y agregarlos a la tabla HTML
  for (var i = 0; i < datos.length; i++) {

    var fila = datos[i];

    var tr = $("<tr>");
    tr.append($("<td>" + fila.id + "</td>"));
    tr.append($("<td>" + fila.nombre + "</td>"));
    tr.append($("<td>" + fila.precio + "</td>"));
tr.append($("<td> <img src='fotos/" + fila.id + ".png' style='width:25px;'> </td>"));

    $("#articulos tbody").append(tr);
  }
});


</script>

</body>
</html>

Comentarios