It does not show all the data of the mysql database in my table

2

     Hi, how are you,

I come with a doubt because it does not show me the data of my mysql database in a table that believes in my html. You skip the first user, it is worth mentioning that you already check my connection, the name of the fields in detail and the links.

Currently I have this like this:

<?php
session_start();

require'funcs/conexion.php';

if(!isset($_SESSION["id_usuario"])){
   header("Location: index.php");
}
?> 

<?php

$sql = "SELECT id, nombre, costo, horario, acercade, edad, sexo, servicios, usuario_municipio FROM usuarios"; 

$stmt = $mysqli->prepare($sql);

if ($stmt) {
    $stmt->execute();
    $stmt->store_result();
    $row = mi_fetchassoc($stmt);
}
// $stmt->free_result();

$mysqli->close();

function mi_fetchassoc($stmt)
{
    if ($stmt->num_rows>0)
    {
        $rs = array();
        $md = $stmt->result_metadata();
        $params = array();
        while($field = $md->fetch_field()) {
            $params[] = &$rs[$field->name];
        }

        call_user_func_array(array($stmt, 'bind_result'), $params);

        if($stmt->fetch())
            return $rs;
    }
    return null;
}
?>



<html>
    <head>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-theme.css" rel="stylesheet">
    <script src="js/jquery-3.1.1.min.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">  

    </head>

    <body>

            <div class="container">
        <div class="row table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>

                            <th>Nombre</th>   
                            <th>Costo</th>
                            <th>Horario</th>
                            <th>Edad</th>
                            <th>Sexo</th>
                            <th>Servicios</th>
                        </tr>
                    </thead>

                    <tbody>
                    <?php while($row = mi_fetchassoc($stmt))
                        { ?>
                    <tr>

                        <td><?php echo $row['nombre']; ?></td>   
                        <td><?php echo $row['costo']; ?></td>
                        <td><?php echo $row['horario']; ?></td>
                        <td><?php echo $row['edad']; ?></td>
                        <td><?php echo $row['sexo']; ?></td>
                        <td><?php echo $row['servicios']; ?></td>
                        <td></td>
                        <td></td>

                    </tr>
                        <?php } ?>
                    </tbody>                    

                </table>
            </div>
        </div>
    </body>
</html>

But it does not show me the first registered user only the others, why would this problem be? sorry for the clutter in the code I still do not know how to order the code.

I hope someone can guide me

Greetings.

    
asked by Noctis 19.09.2018 в 01:22
source

2 answers

5

The problem is that you are eating the first record once you execute the query, here:

$stmt = $mysqli->prepare($sql);
if ($stmt) {
    $stmt->execute();
    $stmt->store_result();
    $row = mi_fetchassoc($stmt); // <== Aquí
}

So when you get here:

            <tbody>
            <?php while($row = mi_fetchassoc($stmt))
                { ?>
            <tr>

now you start from the second record.

Try simply removing the fetch (my_fetchassoc) that exists after the execute. You do not need a fetch at that time. The subsequent code should be in charge of making the fetch.

    
answered by 19.09.2018 / 01:50
source
1

Complement to the answer of @Julio, and because part of your code seems familiar, I must say that mi_fetchassoc was in the not too distant past a function that I had invented to store the result set in an array < strong> when using prepared queries and the mysqlnd driver was not installed.

The case was exposed here in full: How to obtain an associative arrangement using queries prepared with mysqli? and there we can actually see the mi_fetchassoc function. @DBulten's response is optimal for those cases and is what I recommend . If you decide to use it, it would only be enough to recover in a variable what will return the function Arreglo_Get_Result of the answer already mentioned.

For example:

$resultado= Arreglo_Get_Result($stmt);

In $resultado you have your array and you only read it or you pass it to where you want without needing more manipulations.

Here is a full working example .

In summary, if you decide on this function, the code would look like this:

$sql = "SELECT id, nombre, costo, horario, acercade, edad, sexo, servicios, usuario_municipio FROM usuarios"; 
$stmt = $mysqli->prepare($sql);
if($stmt){
    $stmt->execute();
    /*Tendrás los resultados en $arrDatos sin necesidad de ninguna otra manipulación*/
    $arrDatos=myGetResult($stmt);
    $stmt->close();
}
$mysqli->close();

/*
    * FUNCION QUE EMULA EL FETCH_ASSOC DE PDO
    * Esta función nos permite crear un array asociativo con los resultados
    * Así accedemos fácimente a su valor por el nombre de columna en la base de datos
    * Es particularmente útil cuando en el SELECT tenemos muchas columnas
    * porque de lo contrario, tendríamos que hacer un bind de cada columna a mano
    * Esta función se puede incorporar a una clase utilitaria, para re-usarla en
    * todas las consultas que requieran este tipo de operaciones
*/

function myGetResult( $Statement ) {
    $RESULT = array();
    $Statement->store_result();
    for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
        $Metadata = $Statement->result_metadata();
        $PARAMS = array();
        while ( $Field = $Metadata->fetch_field() ) {
            $PARAMS[] = &$RESULT[ $i ][ $Field->name ];
        }
        call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
        $Statement->fetch();
    }
    return $RESULT;
}

But ... do you really need a query prepared in this case?

The query: SELECT id, nombre, costo, horario, acercade, edad, sexo, servicios, usuario_municipio FROM usuarios does not imply any risk of SQL injection, so you can run it without any problem using the query method simply. That way you save:

  • Prepare it
  • Execute it
  • Confront the difficulty of mysqli to store prepared query results explained above

In that case, obtaining an associative array is simpler, like this:

$sql = "SELECT id, nombre, costo, horario, acercade, edad, sexo, servicios, usuario_municipio FROM usuarios"; 
$datos = $mysqli->query($sql);
if($datos->num_rows > 0) {
    $arrDatos=array();
    while ($row = $datos->fetch_assoc())
    {
        $arrDatos[]=$row;
    }
}
 /*Aquí puedes disponer de $arrDatos que será un arreglo asociativo con los resultados*/
 /*Cerrar recursos*/
    
answered by 19.09.2018 в 03:30