简体   繁体   English

如何在PHP中显示MySQL数据库中存储的一个表的所有数据

[英]How to display all the data of a table stored in a MySQL database in PHP

I am trying to display the data of a table containing an image in blob format, but I can only get the last inserted record to be displayed.我试图以 blob 格式显示包含图像的表的数据,但我只能显示最后插入的记录。 I would like to show all the records with their respective images, and when adding a new record it will be shown with the rest of the table data.我想显示所有记录及其各自的图像,当添加新记录时,它将与表数据的 rest 一起显示。

MYSQL MYSQL

noticias: idNoticia(PK), idUser(FK), titulo, imagen(LONGBLOB), texto, fecha noticias: idNoticia(PK), idUser(FK), titulo, imagen(LONGBLOB), texto, fecha

PHP - insertarNoticias.php PHP - insertarNoticias.php

include('./DB.php');
session_start();

$idUser = $_SESSION['usuario'][0];
   $titulo = $_POST['titulo-noticia'];
   $texto = $_POST['texto-noticia'];
   $fecha = $_POST['fecha-noticia'];
   $nombreImagen = $_FILES['imagen']['name'];
   $carpetaDestino = $_SERVER['DOCUMENT_ROOT'] . '/masterD/trabajo_final_php/img/'; 
   move_uploaded_file($_FILES['imagen']['tmp_name'], $carpetaDestino . $nombreImagen);
   
   $conexion = DB::conn();
   $imagen = fopen($carpetaDestino . $nombreImagen, "r");
   $archivoBytes = fread($imagen, intval(filesize($carpetaDestino . $nombreImagen)));
   fclose($imagen);
   
   $sentencia = 'INSERT INTO noticias (idUser, titulo, imagen, texto, fecha) VALUES (:idUser, :titulo, :imagen, :texto, :fecha)';
   $consulta = $conexion->prepare($sentencia);
   $consulta->bindParam(':idUser', $idUser);
   $consulta->bindParam(':titulo', $titulo);
   $consulta->bindParam(':imagen', $archivoBytes);
   $consulta->bindParam(':texto', $texto);
   $consulta->bindParam(':fecha', $fecha);
   $consulta->execute();
   $consulta->closeCursor();
   $conexion = null;

PHP - mostrarNoticias.php PHP - mostrarNoticias.php

include('./DB.php');
session_start();

$titulo = '';
    $imagen = '';
    $texto = '';
    $fecha = '';

    $conexion = DB::conn();
    $sentencia = 'SELECT * FROM noticias';
    $consulta = $conexion->prepare($sentencia);
    $consulta->execute();

    
    while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
        
        $titulo = $row['titulo'];
        $imagen = $row['imagen'];
        $texto = $row['texto'];
        $fecha = $row['fecha'];
        
    }

    $consulta->closeCursor();
    $conexion = null;

PHP - adminNoticias.php PHP - adminNoticias.php

<?php
include('./mostrarNoticias.php');
?>

<form class="form" action="./insertarNoticias.php" method="post" id="crear-noticia" enctype="multipart/form-data">
                            <div class="form-label">
                                <input type="file" name="imagen" class="form-control mb-3" id="imagen-noticia" required>
                                <input type="text" class="form-control mb-3" name="titulo-noticia" id="titulo-noticia" placeholder="Título noticia" required>
                                <input type="text" class="form-control mb-3" name="texto-noticia" id="texto-noticia" placeholder="Texto noticia" required>
                                <input type="date" class="form-control mb-3" name="fecha-noticia" id="fecha-noticia" required>
                            </div>
                            <button type="submit" class="btn btn-success col-12 text-center">
                                Crear noticia
                            </button>
                        </form>

<div class="grid-container pt-4" id="ver-noticias">
            <div class="grid-item">
                <?php
                echo "<h4>$titulo</h4>";
                echo "<p>$texto</p>";
                echo "<p>$fecha</p>";
                echo "<img width='300' height='160' src='data:image/png; base64," . base64_encode($imagen) . "'>";
                ?>
            </div>
        </div>

@LuqMan this is what I mean @LuqMan 这就是我的意思

now it is shown like this现在它是这样显示的

<div class="grid-container">
<div class="grid-item">
<h4></h4>
<p></p>
<p></p>
<img>
<h4></h4>
<p></p>
<p></p>
<img>
</div>
</div>

And I would like it to look like this:我希望它看起来像这样:

<div class="grid-container">
<div class="grid-item">
<h4></h4>
<p></p>
<p></p>
<img>
</div>
<div class="grid-item">
<h4></h4>
<p></p>
<p></p>
<img>
</div>
</div>

You are fetching the data in a loop, over-writing the same variable.您正在循环获取数据,覆盖相同的变量。 You need to display the variables in the loop.您需要在循环中显示变量。 Its best to create a function to display each row and call it from the loop.最好创建一个 function 来显示每一行并从循环中调用它。

One solution is as follows -一种解决方案如下 -

Shift the include down to where the display is将包含向下移动到显示所在的位置

PHP - adminNoticias.php PHP - adminNoticias.php

<form class="form" action="./insertarNoticias.php" method="post" id="crear-noticia" enctype="multipart/form-data">
                            <div class="form-label">
                                <input type="file" name="imagen" class="form-control mb-3" id="imagen-noticia" required>
                                <input type="text" class="form-control mb-3" name="titulo-noticia" id="titulo-noticia" placeholder="Título noticia" required>
                                <input type="text" class="form-control mb-3" name="texto-noticia" id="texto-noticia" placeholder="Texto noticia" required>
                                <input type="date" class="form-control mb-3" name="fecha-noticia" id="fecha-noticia" required>
                            </div>
                            <button type="submit" class="btn btn-success col-12 text-center">
                                Crear noticia
                            </button>
                        </form>

<div class="grid-container pt-4" id="ver-noticias">
<?php
include('./mostrarNoticias.php');
?>
</div>

And show each row here并在这里显示每一行

PHP - mostrarNoticias.php PHP - mostrarNoticias.php

include('./DB.php');
session_start();

$titulo = '';
    $imagen = '';
    $texto = '';
    $fecha = '';

    $conexion = DB::conn();
    $sentencia = 'SELECT * FROM noticias';
    $consulta = $conexion->prepare($sentencia);
    $consulta->execute();

    
    while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
        
        $titulo = $row['titulo'];
        $imagen = $row['imagen'];
        $texto = $row['texto'];
        $fecha = $row['fecha'];
        ?>
        <div class="grid-item">
        <?php
        echo "<h4>$titulo</h4>";
        echo "<p>$texto</p>";
        echo "<p>$fecha</p>";
        echo "<img width='300' height='160' src='data:image/png; base64," . base64_encode($imagen) . "'>";
        ?>
        </div>        
        <?php
    }

    $consulta->closeCursor();
    $conexion = null;

....... …………

The very easy solution is shared here, but there may be alternative of this too.这里分享了非常简单的解决方案,但也可能有其他选择。 The problem in your code is that, your while loop continues its loops and the variables in the loop are replacing its values at each iteration.您的代码中的问题是,您的 while 循环继续其循环,并且循环中的变量在每次迭代时都替换其值。 You can convert each variable to array and then use them in your code where you want to display the table using foreach loop.您可以将每个变量转换为数组,然后在您想要使用 foreach 循环显示表格的代码中使用它们。 But the easiest solution is as below:但最简单的解决方案如下:

PHP - mostrarNoticias.php PHP - mostrarNoticias.php

$output='';
while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {

    $titulo = $row['titulo'];
    $imagen = $row['imagen'];
    $texto = $row['texto'];
    $fecha = $row['fecha'];

    $output .= "<h4>$titulo</h4>
            <p>$texto</p>
            <p>$fecha</p>
            <img width='300' height='160' src='data:image/png; base64," . base64_encode($imagen) . "'>";

}

PHP - adminNoticias.php In your adminNoticias file, replace the following div as below to use the output fetched from previous while loop containing all records. PHP - adminNoticias.php在您的 adminNoticias 文件中,将以下 div 替换为使用从包含所有记录的先前 while 循环中获取的 output。

<div class="grid-container pt-4" id="ver-noticias">
            <div class="grid-item">
                <?php
                echo $output;
                ?>
            </div>
</div>

If you need any explanation, I will appreciate:-)如果您需要任何解释,我将不胜感激:-)

EDITED VERSION AS PER YOUR COMMENT根据您的评论编辑的版本

The DIV element can be embedded in while loop as below: DIV 元素可以嵌入 while 循环中,如下所示:

PHP - mostrarNoticias.php PHP - mostrarNoticias.php

$output='';
while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {

    $titulo = $row['titulo'];
    $imagen = $row['imagen'];
    $texto = $row['texto'];
    $fecha = $row['fecha'];

    $output .= "<div class='grid-container pt-4' id='ver-noticias'>";
    $output .= "<div class='grid-item'><h4>$titulo</h4>";
    $output .="<p>$texto</p>
            <p>$fecha</p>
            <img width='300' height='160' src='data:image/png; base64," . base64_encode($imagen) . "'></div></div>";

}

Now Print the Output in adminNoticias.php file现在在 adminNoticias.php 文件中打印 Output

            <?php
            echo $output;
            ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM