How to scan a vector in PHP

Asked

Viewed 92 times

-2

I’m trying to make a question and answer game in php, already working the comparison, however, I’m having a problem, when I click to answer the vector goes to the last Dice, ie, last question. I tried to put a Rand, but in this case he does the same thing and repeats the same question. I feel like I don’t know where to put the loop.

<?php 






$banco = new mysqli("localhost", "root", "", "db_ingles");
$banco->set_charset('utf8');
if($banco->connect_errno != 0){
    echo "<h1> Erro de conexao no banco</h1>Erro: ". $banco->connect_errno . "</h2>";
}else{
    //conectado
}


$id = 0;
$pergunta= "";
$resposta= "";
$msg= "";
$erros = 0;



if (isset($_POST["btResponder"])) {

    $id = $_POST["id"];
    $pergunta = $_POST["pergunta"];
    $resposta = $_POST["respostacorreta"];





    if(strcasecmp($resposta, $_POST["resposta"]) == 0){
        $msg = "<h1> acertou : $resposta </h1>";

    $sql = "SELECT * FROM perguntas ORDER BY RAND() LIMIT 1";
    $retorno = mysqli_query($banco, $sql); 
    $registro = mysqli_fetch_array($retorno);



    $id = $registro["id"];
    $pergunta = $registro["pergunta"];
    $resposta = $registro["resposta"];

    }else{

        $msg = "<h1> Errada a resposta correta é: $resposta </h1> <br>";



    }

}else{
    // escolher uma pergunta

    $sql = "SELECT * FROM perguntas ORDER BY RAND() LIMIT 1";
    $retorno = mysqli_query($banco, $sql);
    $registro = mysqli_fetch_array($retorno);
    $id = $registro["id"];
    $pergunta = $registro["pergunta"];
    $resposta = $registro["resposta"];



}





 ?>

<?php



 require_once '../config/header.inc.html'; ?>  <!-- Importando o cabeçalho la do arquivo header -->

<div class="row container">
    <div class="col s12">
        <p>&nbsp;</p>



         <!DOCTYPE html>
 <html>
 <head>


    <title>perguntas</title>
 </head>
 <body>


    <h3>Word: <?php echo $pergunta; ?></h3>

    <form method="post" action="#" autocomplete="off">
    <div class="input-field col s12 m6">
    <input type="text" name="resposta" required autofocus/>
    <label for="search">Digite a resposta</label>
    </div>


    <input type="hidden" name="id" value="<?php echo $id; ?>">
    <input type="hidden" name="pergunta" value="<?php echo $pergunta; ?>">
    <input type="hidden" name="respostacorreta" value="<?php echo $resposta; ?>">

    <div class="input-field col s12 m6">
    <input type="submit" name="btResponder" value="Responder" class="btn"/><br><br>
    </div>
    </form>



    <?php echo $msg; ?>





    <script type="text/javascript" src="materialize/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="materialize/js/materialize.min.js"></script>


<script type="text/javascript">
    $(document).ready(function(){

    });

</script>


 </body>
 </html>


    </div>

</div>




<?php require_once '../config/footer.inc.html' ?>  <!-- Importando o rodape la do arquivo footer -->























?>

  • This here for ($i=0; $i<=10; $i++) { $registro = mysqli_fetch_array($retorno); } will always return the last element in record, because it will be a loop of overwriting of the last added value. I don’t understand what you want to do, but if you want to get an array of all the answers you could do for ($i=0; $i<=10; $i++) { $registro[] = mysqli_fetch_array($retorno); }

  • Another option is to use fetch_all()

  • I simply want to pass position by position each time I click to answer. but maybe I’m not sure where to put the go in the right place

  • So you have to put the operations that manipulate $registro within the for. What to do outside the for will always be in the last iterated record.

1 answer

-2


Hello,

See now if it works!

I have already corrected for the answer check to be CASE-INSENSITIVE (either uppercase or lowercase)!

<?php 

/*
MEUS DADOS PARA TESTE

$perguntas = array(

    array(
        'id' => 1,
        'pergunta' => 'sapo',
        'resposta' => 'frog',
    ),
    array(
        'id' => 2,
        'pergunta' => 'vaca',
        'resposta' => 'cow',
    ),
    array(
        'id' => 3,
        'pergunta' => 'leão',
        'resposta' => 'lion',
    )

);

$rand = rand(0,2);
$registro = $perguntas[ $rand ];
*/

// CONECTA NO BANCO DE DADOS
$banco = new mysqli("localhost", "root", "", "db_ingles");

// SE NÃO CONECTA NO BANCO, DIE
if(!$banco) die("<h1>Erro de conexao no banco</h1>Erro: ". $banco->connect_errno);

// SET CHARSET
$banco->set_charset('utf8');

// VARIAVEIS INICIAIS
$mostraMensagemResposta = false;

// RESPOSTA FORNECIDA
if ( isset($_POST["btResponder"]) ) {

    // STATUS DA RESPOSTA
    $isRespostaCorreta = false;

    // TERÁ QUE MOSTRAR UMA MENSAGEM RESPOSTA
    $mostraMensagemResposta = true;

    $postPergunta = $_POST["pergunta"];
    $postRespostaCorreta = $_POST["respostacorreta"];
    $postResposta = $_POST["resposta"];

    // VERIFICA SE A RESPOSTA ESTÁ CORRETA - CASE-INSENSITIVE
    if( strtolower($postRespostaCorreta) === strtolower($postResposta) ){

        $isRespostaCorreta = true;

    }

} // FIM RESPOSTA FORNECIDA

// escolher uma pergunta

$sql = "SELECT * FROM perguntas ORDER BY RAND() LIMIT 1";
$retorno = mysqli_query($banco, $sql);
$registro = mysqli_fetch_array($retorno);

$id = $registro["id"];
$pergunta = $registro["pergunta"];
$resposta = $registro["resposta"];

?>
<?php 
/* CABEÇALHO */
require_once '../config/header.inc.html'; ?>

<?php 

// MOSTRA SE A RESPOSTA ESTÁ CORRETA OU ERRADA
if($mostraMensagemResposta === true){ 

?>
<div class="row container">
    <div class="col s12">
        <p>Word: <?php echo $postPergunta; ?><br>
        Sua reposta: <?php echo $postResposta; ?><br>
        <strong>ESTÁ <?php echo $isRespostaCorreta === true ? 'CORRETA' : 'ERRADA'; ?></strong>
        <?php if($isRespostaCorreta === false){ ?><br>Correto: <strong><?php echo $postRespostaCorreta ?></strong> <?php }?>
        </p>
    </div>
</div>
<?php } // FIM MOSTRAR RESPOSTA ?>
<div class="row container">
    <div class="col s12">
    <h3>Word: <?php echo $pergunta; ?></h3>
    <form method="post" action="" autocomplete="off" enctype="multipart/form-data">
    <div class="input-field col s12 m6">
    <input type="text" name="resposta" required autofocus/>
    <label for="search">Digite a resposta</label>
    </div>
    <input type="hidden" name="id" value="<?php echo $id; ?>">
    <input type="hidden" name="pergunta" value="<?php echo $pergunta; ?>">
    <input type="hidden" name="respostacorreta" value="<?php echo $resposta; ?>">

    <div class="input-field col s12 m6">
    <input type="submit" name="btResponder" value="Responder" class="btn"/><br><br>
    </div>
    </form>
    <script type="text/javascript" src="materialize/js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="materialize/js/materialize.min.js"></script>
<?php 

// Importando o rodape la do arquivo footer
require_once '../config/footer.inc.html' 

?>

The tests here worked!

It had html tag after div tag! I also removed!

I hope I’ve helped! Anything, just put in the comments!

  • It’s just a table the other select exists but it’s the same table was just an error at the time I pasted the code here

  • Got it! So you don’t really need the 2! If you want more help, you’d have to give more details (Database Structure, PHP code and HTML code! Maybe the problem is the amount of data in the table and the same Select!

  • Augusto Vasques Thanks for trying to help I will put the full code, I removed the loop because it was not working the way I would like, I left only the Rand , but when I click to reply it makes the select again and there repeats words. I simply want to pass position by position each time I click reply. (I updated the code).

  • I updated the answer!

  • @maxmodle if helped, please evaluate the answer :)

  • Thanks for the help, it was much cleaner the code with the variable boleanas, however, it is still repeating the ID at the time of choice here comes the same question, trying to find a way to sweep the vector one by one in a loop without returning and I think the RAND() will not be able I tried. where id = "$id" and in each loop I incremented + 1 in the variable id to get the next id only then it swept the vector to the end and could not

  • I never used the functions mysqli... mysql old jump straight to PDO! This may be the problem! Try adding in the query WHERE id != $idPerectAnterior... you can also store all answered questions in $_SESSION and filter through them all.... if you wait a while, I can study mysqli to help you more...

  • Ah, you running this query on phpMyAdmin, or any other interface, EACH TIME COMES A DIFFERENT QUESTION?

  • I am also studying PDO, because I think it is safer, but as this is a system just for my use I did the same msqli. Yes each time a different question starting from id 1 to table last

  • What I asked is if QUERY is working? RAND... Tests out of PHP... in Heidsql or phpMyAdmin....

  • Ta working yes, I tested in phpMyAdmin it selects 1 question "limit 1'' I have to think of a way not to use the RAND and selects 1 id at a time in a loop

  • I’ve made a new response to your change of plans! I still don’t think you’re handling your duties well mysqli! I hope I’ve helped!

  • Duda Gervásio got it, but I think it’s a ganbiarra but it worked well kkkk, I could not make the loop to increment the variable pq every time I clicked the button it restarts the variable there inside the if of the button I did an uptade and increment. For this I created a table with a field and then I make the increment inside the bank and put in the variable and pick it and put in the select of the question and get the next id. I know this is not the right way but it worked out Valew Duda Gervasio

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.