get the user name to show it once the session starts with php mysql html

1

I have a question with this code is that it does not show me the name of the user, in itself what I ask is how you can show the name of the user who started the session, and who appears in the corner of the website thanks to beforehand

note: when the session starts in the part where the name of the user who started the session should show me hello

this is the code that allows you to start the session

    <?php //archivo para verfificar si existe usuario en la base de datos, es que verifica el login
session_start();
include 'conexionpadmi.php';

$usuarioestudiante= $_POST['usuarioestudianteform'];
$passwordestudiante=$_POST['passestudiante'];

$c= new OperacionesMysql();
$con=$c->Conectar();

$queryes = "SELECT * FROM tablaestudiante WHERE nombreestudiante='".$usuarioestudiante." ' AND pwestudiante= '".$passwordestudiante."'";

$qes= mysqli_query($con, $queryes);

if (mysqli_fetch_assoc($qes)) 
         {
            $resultpro = mysqli_fetch_assoc($qes);

            echo 2;

            $_SESSION['login']='hola';
         }

mysqli_close($con);
 ?>

and the html code here is where the name of the user obtained in the code above is displayed

<td id="idcelda1"  >
                <!--celda 1-->
                <label id="idnombreusuario">Nombre De Usuario:<?php echo '<h1 align=center>'.$_SESSION["login"].'</h1>'; ?> </label>
            </td>

this is the ajax code to run the login

$('#botonokestudiante').click(function(){
      var datos=$('#formestudinte').serialize();

       if ($('#nombreestu').val().trim() === '') {
        modalnombrevacio();

        return false; 
      } 

      if ($('#contraseñaestu').val().trim() === '') {
        modalpassvacio();

        return false; 
      } 

       $.ajax({
        type:"POST",
        url:"../modelos/verificaloginestudiante.php",
        data:datos,
        cache: "false",
        beforeSend:function(){
          $('#botonokestudiante').val("conectando...");
        },
        success:function(data){
          $('#botonokestudiante').val("ingresar");
          if(data == 2){
             Limpiar();
              $(location).attr('href','../vistas/paginaestudiante.php');

          }else{

            Limpiar();
          }


        }
      });



        return false;
    });

html code of the form

<form id="formestudinte">
        <div id="r2" class="animated fadeIn">
        <input type="text" name="usuarioestudianteform" id="nombreestu" placeholder="Usuario"  maxlength="10">

        <input type="password" name="passestudiante" id="contraseñaestu" placeholder="Contraseña"  maxlength="10">

        <input type="submit" value="ingresar" name="ok" id="botonokestudiante">

        <button id="regresaropcionesestu">Inicio</button>

        </div>

        </form>

full html code of the page where the user's name is displayed

<?php 
session_start();
if (isset($_SESSION['login'])) {

    ?>
<!DOCTYPE html>
<html>
<head>
    <title>principal</title>
    <meta charset="utf-8">
     <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
     <link rel="stylesheet" type="text/css" href="../recursos/css/estilopaginaestudiante.css">

     <link rel="stylesheet" type="text/css" href="../recursos/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" type="text/css" href="j../recursos/js/alertifyjs/css/themes/default.css">
     <link rel="stylesheet" type="text/css" href="../recursos/js/alertifyjs/css/alertify.css">
     <link rel="stylesheet" href="../recursos/css/animate.css">

     <script src="../recursos/js/jquery-3.3.1.js"></script>
     <script src="../recursos/bootstrap/js/bootstrap.min.js"></script>
    <script src="../recursos/js/alertifyjs/alertify.js"></script>

    <script src="../recursos/js/jspaginaestudiante.js"></script>

    <script> 
    $(function(){
      $("#nivel1").load("niveles/nivel1.php"); 

      $("#nivel2").load("niveles/nivel2.php"); 

      $("#nivel3").load("niveles/nivel3.php"); 

      $("#nivel4").load("niveles/nivel4.php"); 

      $("#nivel5").load("niveles/nivel5.php"); 
    });
    </script> 

</head>
<body>

<div id="contenedor">

<div id="nivel1"></div>

<div id="nivel2"></div>

<div id="nivel3"></div>

<div id="nivel4"></div>

<div id="nivel5"></div>
    <!-- niveles -->
    <table id="tablecuerpo" >
        <tr>
            <td id="idcelda1"  >
                <!--celda 1-->
                <label id="idnombreusuario">Nombre De Usuario:<?php echo $_SESSION["login"]; ?> </label>
            </td>
            <td id="idcelda2">
                <!--celda 2-->
                <button id="idbotoncerrarsesion">Cerrar Session</button>

            </td>
        </tr>
        <tr>
            <td id="idcelada3" colspan="2">

            <!--celda3-->

            <button id="idbotonnivel1" class="diseñobotonnivel">nivel 1</button>
            <button id="idbotonnivel2" class="diseñobotonnivel">nivel 2</button>
            <button id="idbotonnivel3" class="diseñobotonnivel">nivel 3</button>
            <button id="idbotonnivel4" class="diseñobotonnivel">nivel 4</button>
            <button id="idbotonnivel5" class="diseñobotonnivel">nivel 5</button>
            </td>
        </tr>

    </table>


</div>

<div id="imagenizquierda">
    <img src="../recursos/svg/fondo1.svg" id="fondoindex1">

    <img src="../recursos/svg/fondo2.svg" id="fondoindex2">

</div>


        <div id="modalcerrarsessionn" class="animated bounceIn" >
        <p id="parrafochequeavacio">Deseas Cerrar Session</p>
        <button type="button" id="botonclosemodalpaginaestudinte" class="btn btn-secondary">Si</button>
        <button type="button" id="closemodalcerrarsession" class="btn btn-secondary">Cerrar</button>
        </div>

</body>
</html>


    <?php
}else{
    echo "no puede iniciar session";
    header("Location: index.php");
}

 ?>

complete html code of the login and where are the forms

<?php 
session_start();
session_destroy();
//unset($_SESSION['login']);
if (isset($_SESSION['login'])) {
    //echo "bienbenido session ".$_SESSION['login'];
}else{
    //echo "sin session";
}



 ?>

<!DOCTYPE html>
<html>
<head>
    <title>principal login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0,maximun-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" type="text/css" href="../recursos/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="j../recursos/js/alertifyjs/css/themes/default.css">
    <link rel="stylesheet" type="text/css" href="../recursos/js/alertifyjs/css/alertify.css">
    <script src="../recursos/js/jquery-3.3.1.js"></script>
    <script src="../recursos/js/alertifyjs/alertify.js"></script>
    <script src="../recursos/js/controlesindex.js"></script>
    <script src="../recursos/js/jsquerylogin.js"></script>

    <script type="text/javascript" src="../recursos/js/codigojslogin.js" ></script>
    <link href="../recursos/css/estiloslogin.css" type="text/css" rel="stylesheet">
<link rel="stylesheet" href="../recursos/css/animate.css">

</head>
<body>

<!--<img id="imagenfondobody" class="animated fadeIn" src="../recursos/svg/dibujo3.svg">-->

<div id="contenedor">

<div id="modalnombrevacio" class="animated bounceIn">
        <p id="parrafochequeavacio">Debes Agregar El Nombre</p>
        <input type="radio" name="radiomodalchequeavacio" id="pulsacerramodalchequeavacio" >
        <label for="pulsacerramodalchequeavacio" id="botonmodalchequeavacio"><p class="textologin" id="textobotonregistrar" onclick="cerrarmodalnombrevacio();"  >Cerrar</p></label>
        </div>

        <div id="modalpassvacio" class="animated bounceIn">
        <p id="parrafochequeavacio">Debes Agregar La Contraseña</p>
        <input type="radio" name="radiomodalchequeavacio" id="pulsacerramodalchequeavacio" >
        <label for="pulsacerramodalchequeavacio" id="botonmodalchequeavacio"><p class="textologin" id="textobotonregistrar" onclick="cerrarmodalpassvacio();"  >Cerrar</p></label>
        </div>

        <div id="modalusuarionoencontrado" class="animated bounceIn">
        <p id="parrafochequeavacio">Usuario No Existe</p>
        <input type="radio" name="radiomodalchequeavacio" id="pulsacerramodalchequeavacio" >
        <label for="pulsacerramodalchequeavacio" id="botonmodalchequeavacio"><p class="textologin" id="textobotonregistrar" onclick="cerrarmodalusuarionoencontrado();"  >Cerrar</p></label>
        </div>

        <div id="modalmodificausuario" class="animated bounceIn">
        <p id="parrafochequeavacio">Usuario Modificado Con Exito</p>
        <input type="radio" name="radiomodalchequeavacio" id="pulsacerramodalchequeavacio" >
        <label for="pulsacerramodalchequeavacio" id="botonmodalchequeavacio"><p class="textologin" id="textobotonregistrar" onclick="cerrarmodalmodificausuario();"  >Cerrar</p></label>
        </div>

    <form id="formulario" method="post"  name="formalarioprincipal" onsubmit="return validardatosvacion()">

        <div id="zonalogin" class="animated fadeIn">


        <input type="radio" name="radiologinregistra" id="pulsalogin" >
    <label for="pulsalogin" id="iniciarseccionboton"><p class="textologin">Diseño de un software Educativo de la Asignatura castellano para el CEIS "MARIA VELASQUEZ DE ROJAS"</p></label>



        </div>
        <!--<p id="pnombre">Nombre:</p>-->
        <div id="r1" class="animated fadeIn">
        <input type="text" name="cedeulaform" id="nombre" placeholder="Cedula"  maxlength="10">

        <input type="password" name="pwprofesor" id="contraseña" placeholder="Contraseña"  maxlength="10">

        <input type="submit" value="ingresar" name="ok" id="botonok">

        <button id="recuperarcuentausuario" >Recuperar Cuenta</button>
        <button id="regresaropciones">Inicio</button>
        </div>
        </form>

        <form id="formestudinte" method="POST">
        <div id="r2" class="animated fadeIn">
        <input type="text" name="usuarioestudianteform" id="nombreestu" placeholder="Usuario"  maxlength="10">

        <input type="password" name="passestudiante" id="contraseñaestu" placeholder="Contraseña"  maxlength="10">

        <input type="submit" value="ingresar" name="ok" id="botonokestudiante">

        <button id="regresaropcionesestu">Inicio</button>

        </div>

        </form>

        <div id="seccionopciones" class="animated fadeIn">
            <button id="opcionprefe">Profesor</button>
            <button id="opcionestu">Estudiante</button>
        </div>

    <!--modal modifica administrador-->

    <!--<img id="fondo1" src="img/fondo1.png">-->

    <div id="imagenizquierda">
    <img src="../recursos/svg2/pruebafonfoindex22.svg" id="fondoindex1" style="position: absolute; right: 74%; bottom: -280%;width: 40vmax;height: 40vmax; z-index: -1;">

    <img src="../recursos/svg2/figura11.svg" id="figura1" style="position: absolute; right: -110%; bottom: -340%; width: 45vmax;
    height: 45vmax;" >

    <img src="../recursos/svg2/figuras2.svg" id="figura2" style="position: absolute; right: 122%; bottom: 58%; width: 20vmax;
    height: 20vmax;">
    <!--<img id="fondo1" src="img/img2.png">-->
    </div>


                         <div id="modaldivcuentaadministrador">
                    <!--cuenta administrador-->

                    <div>
                        <?php 
                        require_once '../modelos/conexionpadmi.php';

                        $c= new OperacionesMysql();
                        $conexion=$c->Conectar();
                            $sql= "SELECT * FROM tablaadministrador WHERE idadmi= 2";
                            $rs=mysqli_query($conexion, $sql);
                            //$row = mysqli_fecth_array($rs);

                            $row = mysqli_fetch_assoc ($rs);
                        ?>
                        <form  id="formadmii" method="POST">

                            <table cellpadding="10%">
                                <tr>
                                    <td colspan="2">    
                                        <label>Nombre Del Administrador:</label>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <input type="text" class="diseñocajatext" name="nombreusuario" value="<?=$row["nombreadmi"]?>">
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <label>Contraseña Del Administrador:</label>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2">
                                        <input type="text" class="diseñocajatext" name="passusuario" value="<?=$row["pwadmi"]?>">
                                    </td>
                                </tr>
                                <tr>
                                    <td >
                                        <button type="reset" class="btn btn-danger" id="cerrarmadalmodificausuario" onclick="cerrarmodalmodificausuario();">Cancelar</button>
                                    </td>
                                    <td>
                                        <button type="submit" class="btn btn-info" name="updateadmi" id="idupdateadmi">Modificar</button>
                                    </td>
                                </tr>
                            </table>






                        </form>

                    </div>

                 </div>


</div>


</body>
</html>
    
asked by olacris 08.12.2018 в 21:17
source

3 answers

2

First of all, I welcome you to Stackoverflow.

You have several errors in the code you submit. I list the main ones and I will propose a solution:

  • You can not use mysqli_fetch_assoc twice, each time you use it the data pointer moves.
  • When you use mysqli_fetch_assoc you should find the associated data by the name of the column, something like $fila["columna"] . Anyway, we will reject, for this case this way of obtaining the data, opting for another more convenient ...
  • You should check the POST variables
  • It would be nice to apply prepared queries, you can inject dangerous code if you pass the data directly to execution with query . Here I have used prepared queries, I have written an% explicit% of the column that is needed and I used SELECT to get the data. It seems laborious, but it is the price to pay for the security of the data and even of the same system. SQL injection is a danger that should never be minimized.
  • I've given more consistency to the code, for example including the file only when I'm sure I'm going to need it. Also, to gain in coherence and in clarity I wrote everything in the object-oriented style.

This is the code. I've done it on the fly. I hope you have no errors. If there is a problem or you do not understand something, you can say it in comments.

I hope it serves you.

PHP

<?php
    session_start();
    /*Vamo a evitar variable kilométricas*/
    $usr=  ( empty($_POST['usuarioestudianteform']) ) ? NULL : $_POST['usuarioestudianteform'];
    $pass= ( empty($_POST['passestudiante']) )        ? NULL : $_POST['passestudiante'];

    if ($usr && $pass){
        include 'conexionpadmi.php';
        $c= new OperacionesMysql();
        $con=$c->Conectar();
        $sql="SELECT nombreestudiante FROM tablaestudiante WHERE nombreestudiante=? AND pwestudiante=? LIMIT 1";
        if( $stmt = $con->prepare($sql) ){
            $stmt->bind_param("ss", $usr,$pass);
            $stmt->execute();
            $stmt->bind_result($nombre);
            $stmt->fetch();
            $_SESSION['login']=$nombre;
            $arrResult["nombre"]=$nombre;
            //print_r($_SESSION);
            $stmt->close();
            $con->close();
        } else {
            $arrResult["error"]="Error preparando la consulta :".$con->error;     
        }

    } else {
        $arrResult["error"]= "Hay datos vacíos en el POST";
    }
    header('Content-Type: application/json; charset=utf-8');
    echo json_decode($arrResult);   
?>

Javascript

Try your Ajax request in this way (I have omitted the call to bind_result because it does not do anything, if you are interested then you put it in. When you are learning avoid using confusing functions in the code.

The fundamental thing is to understand a thing. The server will respond to Ajax with a JSON object that it may have, either a key Limpiar() or a key error . In the nombre of the Ajax request, it will be verified if the object has the key done , showing in that case a error (that can be changed if you want) and if it will not show the value of the key alert .

I focused here on the Ajax petition, insert it in the context of your code. You will see that I use nombre and done . That's because fail and success are obsolete since jQuery 3.

var request = $.ajax({
    method: "POST",
    url:"../modelos/verificaloginestudiante.php",
    data:datos,
    dataType: "json", 
    cache: "false",
    beforeSend: function(){
                    $('#botonokestudiante').val("conectando...");
                }
});

request.done(function( data ) {
    $('#botonokestudiante').val("ingresar");
    /*Verificamos si no hubo errores en el servidor*/
    if( data.hasOwnProperty("error"){
        alert(data.error);
    }else{
        /*Si no hubo errores el JSON debe tener una clave nombre que se le mando desde PHP*/
        $('#idnombreusuario').val(data.nombre);
    }
});

request.fail(function( jqXHR, textStatus ) {
  alert( "Hubo un fallo en la petición: " + textStatus );
});

Try this way and if there is any problem and difficulty you say it in comments. Keep in mind that the PHP code has also changed, to adapt it to the type of data that the Ajax request expects.

    
answered by 08.12.2018 в 21:47
0

Look, what it says @ A.cedano has a lot worth taking into account, if you say that the code does not work for you and yours if, then you just do what it says @ A.cenado in your answer.
in your variable $_SESSION['login']='hola'; change the 'hello' so you return the variable $resultpro and make reference to the field 'nombre' or as it is called in your table that is: $_SESSION['login']= $resultpro['nombre'];
That way it is possible that you stay as you want.
Greetings.

    
answered by 09.12.2018 в 06:15
0

If you say the code is fine but shows you a Hola instead of the name, then put $nombre

if (mysqli_fetch_assoc($qes)) {
            $resultpro = mysqli_fetch_assoc($qes);
            echo 2;
            $_SESSION['login']='hola';
            // he aqui el error
            $_SESSION['login']=$nombre;
            // claro sera desde la DB
            $fila= mysql_fetch_array ($resultpro);
            $_SESSION['login']=$fila['nombre'];
}
mysqli_close($con);
 ?>

I could vary the syntax but that's where your doubt is

    
answered by 10.12.2018 в 05:07