How to show all the contents of a Mysql table in PHP?

2

I want to make people with the reader role, only see the contents of their rows, but the administrator sees everything, I'm using this code but I do not understand why it does not work. I do not see where the error is here in the logic, because when I want to show all the tables I use $ query2 that selects everything from user

<?php
session_start();
include 'conexion.php';


	$id_sesion = $_SESSION['id'];
	$consulta = mysqli_query ($conn, "SELECT * FROM Usuario WHERE id = '". $id_sesion . "'" );
	$consulta2 = mysqli_query ($conn, "SELECT * FROM Usuario" );
	

	

	// error mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in ----->  
	// se arreglo viendo el error asi 'if (!$consulta){ echo mysqli_error ($conn);}' resulta que escribi mal la tabla, usarlo para ver mas errores


	// https://www.w3schools.com/php/func_mysqli_query.asp
	// mysqli_query(connection,query,resultmode);
	// https://www.w3schools.com/sql/ 

	if ((mysqli_num_rows ($consulta)> 0) || $_SESSION['cargo'] = "lector")
		//  mysqli_num_rows ($consulta) va a ser igual  al numero de columnas, de la misma manera que  "Mysqli_query ($conn, "SELECT * FROM Usuarios")"  sera igual al valor que lleva dentro del parentesis. Por lo que si es mayor a 0, osea si hay columnas en la consulta, viendo asi que fue satisfactoria, se hace lo siguiente.

//array es fila (<-- -->), no columna 
	{

		echo "<p> <br>"; // <------ sin esto no se muestra nada de los echos de abajo


		// mysqli_fetch_array(result,resulttype);
		// [result ]= Mysqli_query(), mysqli_store_result() or mysqli_use_result()
		// [resulttype ] = MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH
		while ($row = mysqli_fetch_array($consulta, MYSQLI_ASSOC)  )
			// otro error: Use of undefined constant MYSQL_ASSOC - assumed 'MYSQL_ASSOC'
			// use esto "if (!$row){ echo mysqli_error ($MYSQLI_ASSOC);}" resulta que coloque MYSQL_ASOC, cuando tuvo que ser MYSQLI_ASSOC
			// https://www.phpclasses.org/discuss/package/9199/thread/4/

			{

			//https://stackoverflow.com/questions/2970936/how-to-echo-out-table-rows-from-the-db-php#
			echo "<tr>";

			echo "
			<table>
				<thead>
					<tr>
						<th>Nombre </th>
						<th>Fecha creacion </th>
						<th>Nick </th>
						<th>Telefono </th>
						

				</thead>
			";

			echo " <td>".$row['nombre']."</td>";
			echo " <td>".$row['fecha_creacion']."</td>";
			echo " <td>".$row['nick']."</td>";
			echo " <td>".$row['telefono']."</td>";
			echo "</tr></table>";



		}



	}

else if ((mysqli_num_rows ($consulta2)> 0) || $_SESSION['cargo'] = 'admin')

{
	echo "<p> <br>";

		while ($row = mysqli_fetch_array($consulta2, MYSQLI_ASSOC)  )
			{
			echo "<tr>";

			echo "
			<table>
				<thead>
					<tr>
						<th>Nombre </th>
						<th>Fecha creacion </th>
						<th>Nick </th>
						<th>Telefono </th>
						

				</thead>
			";

			echo " <td>".$row['nombre']."</td>";
			echo " <td>".$row['fecha_creacion']."</td>";
			echo " <td>".$row['nick']."</td>";
			echo " <td>".$row['telefono']."</td>";
			echo "</tr></table>";



		}
}



//Se te está pasando regresar $respuesta en formato JSON y su encabezado
header('Content-Type: application/json');
?>

Annex some images showing how, regardless of their position, they still show the same thing.

EDIT FOR ANNEXES image of how it looks now when replacing the "else if" with "if" and the backend responsible for creating $ _ SESSION ['charge'] by it seems that there is the problem, it does not seem to recognize it, I do not know if I made a mistake there.

<?php
session_start();
include_once 'conexion.php';
//Declaramos un arreglo que será nuestro retorno
$respuesta = array();

//Primero hay que validar que las variables existan
//La superglobal $_REQUEST responde a los verbos GET y POST
if( empty( $_REQUEST['pwd'] ) || empty( $_REQUEST['nick'] ) ){
  $respuesta['mensaje'] = 'Usuario y/o password vacío';
}


else{
  //Guardamos y limpiamos las variables
  $pwd= mysqli_real_escape_string($conn, $_REQUEST ['pwd']);
  $nick= mysqli_real_escape_string($conn, $_REQUEST ['nick']);

  //Creamos el SQL, no siempre funciona agregando así las variables, yo recomiendo concatenar
  $sql = "SELECT * FROM Usuario WHERE nick = '". $nick. "' AND password = '".$pwd ."'"; 

  //Validamos que la consulta esté bien hecha

  $result = mysqli_query ($conn, $sql);

  if (mysqli_num_rows ($result)> 0)
    //  mysqli_num_rows ($result) va a ser igual  al numero de columnas, de la misma manera que  "Mysqli_query ($conn, "SELECT * FROM Usuarios")"  sera igual al valor que lleva dentro del parentesis. Por lo que si es mayor a 0, osea si hay columnas en la consulta, viendo asi que fue satisfactoria, se hace lo siguiente.
{
          //Aquí asignamos nuestro arreglo, assoc o array te sirven
      $row = mysqli_fetch_array( $result );

      //creas tus variables de sesión
      $_SESSION['id'] = $row['id'];
      $_SESSION['nick'] = $row['nick'];
      $_SESSION['cargo'] = $row['cargo'];
      $respuesta['mensaje'] = 'Se crearon las variables de sesión, conexión exitosa';

      //Recuerda que por limpieza del servidor, borramos la información de la query y cerramos conexión
      mysqli_free_result($result);
      mysqli_close( $conn );

}

  else{
      $respuesta['mensaje'] = 'Nombre de usuario y/o contraseña incorrecta';

  }

}

//Ahora si, retornamos nuestra respuesta con formato y encabezado JSON
header('Content-Type: application/json');
echo json_encode($respuesta);
?>

Topic solved.

    
asked by Hoozuki 30.08.2018 в 16:14
source

2 answers

1

reading the code there are two main problems:

  • Of logic in which you must first ask what type of charge have, so you do not always execute the 2 sentences, you just have to execute what you need and if the condition is fulfilled.
  • At each loop of the cycle you created the same table with the same header, so I was always going to print the last row.
  • said the above, your code should be like this:

    <?php
    session_start();
    include 'conexion.php';
    
    //creas una variable con el contenido base de la tabla
    
    $tabla = "
          <table>
            <thead>
              <tr>
                <th>Nombre </th>
                <th>Fecha creacion </th>
                <th>Nick </th>
                <th>Telefono </th>
        </thead>
          ";
    
    //pregunta primero que tipo de usuario es 
    if ($_SESSION['cargo'] == "lector") {
      //como es un lector necesitaras el id
      $id_sesion = $_SESSION['id'];
      //ejecutas la sentencia sql
      $consulta = mysqli_query ($conn, "SELECT * FROM Usuario WHERE id = '". $id_sesion . "'" );
      //preguntas si trajo resultados
      if ( $consulta->num_rows > 0)
      {
    
    
        //rescorres los resultados que haya traido
        while ($row = mysqli_fetch_assoc($consulta) )
        {
          //como ya tenemos la base de la tabla aqui le sumamos las filas
          $tabla.= "</tr>";
          $tabla.= " <td>".$row['nombre']."</td>";
          $tabla.= " <td>".$row['fecha_creacion']."</td>";
          $tabla.= " <td>".$row['nick']."</td>";
          $tabla.= " <td>".$row['telefono']."</td>";
          $tabla.= "</tr>";
        }
      }
    
    }
    else if ($_SESSION['cargo'] == 'admin'){
      //como es un aministrador no necesitamos id
      $consulta2 = mysqli_query ($conn, "SELECT * FROM Usuario" );
      //preguntamos si trae registros
      if($consulta2->num_rows > 0){
    
          while ($row = mysqli_fetch_assoc($consulta2))
          {
            //sumamos las filas que trae
            $tabla.= "</tr>";
            $tabla.= " <td>".$row['nombre']."</td>";
            $tabla.= " <td>".$row['fecha_creacion']."</td>";
            $tabla.= " <td>".$row['nick']."</td>";
            $tabla.= " <td>".$row['telefono']."</td>";
            $tabla.= "</tr>";
          }
      }
    }
    
    //aqui cierras la tabla
    $tabla.= "</table>";
    //la imprimes
    echo $tabla;
    
    header('Content-Type: application/json');
    ?>
    

    EDITING . there was a parenthesis of more and missing the echo

    I hope you serve, you tell me ...

        
    answered by 30.08.2018 / 16:44
    source
    0

    The first query

     "SELECT * FROM Usuario WHERE id = '". $id_sesion . "'"
    

    is incorrect because the id field is numeric (or at least, it should be if it is the primary key and you used the normalization rules), it should not be treated as a string. It should be like this:

    "SELECT * FROM Usuario WHERE id=". $id_sesion
    

    Although this query will only return a result because if the id the primary key is never repeated, therefore can only have one value (or none)

    The second query is correct, it will return all the results but, as it is in a else if it is likely that it does not enter that condition. The recommendable thing is to replace the else if with a if .

        
    answered by 30.08.2018 в 16:26