How do I print array on the selected segment and location one at a time?

Asked

Viewed 156 times

0

<div class="col-md-2 col-sm-2">

    <form method="post" action="atracoes_resultados.php">
        <h4>Escolha o Segmento:</h4>
        <input type="checkbox" name="csg[]" value="ecologico"> Ecológico<br>
        <input type="checkbox" name="csg[]" value="cultural"> Cultural<br>
        <input type="checkbox" name="csg[]" value="religioso"> Religioso<br>
        <input type="checkbox" name="csg[]" value="rural"> Rural<br><br>

        <h4>Escolha a Localidade:</h4>
        <input type="checkbox" name="csg[]" value="cidade"> Cidade<br>
        <input type="checkbox" name="csg[]" value="estrada"> Estrada AM 352<br>
        <input type="checkbox" name="csg[]" value="rio"> No Rio Negro<br>
        <input type="checkbox" name="csg[]" value="anavilhanas"> No Parque Anavilhanas<br>
        <input type="checkbox" name="csg[]" value="jau"> No Parque Jaú<br><br>
        <input type="hidden" name="acao" value="enviar" />
        <input id="submeter" type="submit" value="Busca">
        </h3>
    </form>  
    <br>                            
</div><!-- form -->
<div class="col-md-2 col-sm-2 lateral"> 
<?php
    if(isset($_POST['acao']) && $_POST['acao'] == 'enviar'){        
    if(!empty($_POST['csg'])){
        $campo = $_POST['csg'];
        foreach($campo as $value){  
                $banco = mysql_query("SELECT * FROM atracoes WHERE segmento  LIKE '%$value%'"); 
                    while($lnbusca = mysql_fetch_array($banco)){    
?>
<?php

                        echo '<img src="'.$lnbusca['thumb'].'" height="50" width="150" class="img-responsive">';
                        ?>
                        <a href="emitir_recibos.php?id=<?php echo $lnbusca['id']; ?>" target="_blank"><FONT face="verdana" COLOR="#996633" class="clicavel"><?php echo $lnbusca['segmento']; ?><?php echo " e "; ?><?php echo $lnbusca['localidade']; ?></font></a>     
                        <?php
                        echo '<hr>';            

                        ?>


<?php

                    }
                            }
                                }
    else{
        echo "<h1>Atração não selecionada</h5>";
    }//-- empty --/
    }//-- isset --/
?>

</div>
  • I don’t understand your question. Do you want to print all the vector fields or just want to show the fields to know the index names? In the second option you can use var_char. In the first option, if it is a lot of data, you can use a "loop for" or "foreach"

  • Good morning. wmsouza changed my question increasing my doubt, hehe.

  • Good morning. wmsouza changed my question increasing my doubt, hehe. I only need to print on the screen, two choices in the checkbox (which will search in the mysql database, type: select ecological and also city, only the data with segment and city, which are in the database, will appear on the screen). I have a table of attractions, where I have two columns SEGMENT and LOCALITY, I want to return only the records that contain the choices by the user in the checkbox. I hope I have improved the question.

  • Someone to help me? : (

  • Now I get it! You should add a Listener check in the checkbox (pure javascript or jQuery) that when checked you take the checkbox value and send it to a PHP page using Ajax. This PHP page does the query and returns the segment/locale in JSON. Inside the Ajax that sent the data you can print using a loop. It’s quite a lot...

  • Do not use mysql_query, use PDO.

  • I’m starting php/mysql, and I thought it was possible to recover SEGMENT and LOCALE data simultaneously (from the checkbox in the above code) just using the above routine. When choosing the segment, the code prints correctly on the screen only the choice (of the segment). Already the locality (which should be linked to only 1 (hum) segment chosen), disappears. There is at least one way to recover it?

  • You can catch them simultaneously on the php page that receives this form, but for that you need to give different names to segment and locality checkboxes. " csg[]" is a vector of segments, give another name to the locale. So, in php, you give $_POST on these two vectors

  • Is this form in the code static (the way it is there) or is it filled with SQL data? Every time I open the question I get more confused haha it seems something very simple, I just need to understand 100%

  • The form is static, the data is only in the checkbox, but when retrieving them, it is that the headache begins in manipulating the condition to return only what was clicked. The problem is that everything is being recovered from the bank.

  • It goes like this: there are 4 segments, and each segment is composed of all the localities . If I choose ecological + city and submit, the desire is to have only the ecological events that occur in the city (being that also the other three segments tb have events in the city, but I do not want them in the result of the search).

  • Aah perfect! Add your database structure to the question that I will create the answer for you. It can be the SQL that creates and fills, for me to reproduce here.

  • I could not edit my question, but I will post here: bank: SEMTUR table: attractions. id int(5) AUTO_INCREMENT name1 varchar(200) utf8_general_ci segment varchar(200) utf8_general_ci Nome2 text utf8_general_ci locality varchar(200) utf8_general_ci Thumb text utf8_general_ci

  • If you don’t understand, I’ll send a better one.

  • I’m done. I use PDO because I’m familiar, anything you can change to whatever you want (mysqli). I’ll edit and post

  • On hold.....

Show 11 more comments

1 answer

0


I made a jQuery Ajax request from the form page for the file connecting to the database. Using the JSON result to "write" to a DIV.

HTML page:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <script src="eventos.js"></script>
    </head>

    <body>
        <form method="post" id="form-seg-loc">
            <h4>Escolha o Segmento:</h4>
            <input type="checkbox" name="csg[]" value="ecologico"> Ecológico<br>
            <input type="checkbox" name="csg[]" value="cultural"> Cultural<br>
            <input type="checkbox" name="csg[]" value="religioso"> Religioso<br>
            <input type="checkbox" name="csg[]" value="rural"> Rural<br><br>

            <h4>Escolha a Localidade:</h4>
            <input type="checkbox" name="loc[]" value="cidade"> Cidade<br>
            <input type="checkbox" name="loc[]" value="estrada"> Estrada AM 352<br>
            <input type="checkbox" name="loc[]" value="rio"> No Rio Negro<br>
            <input type="checkbox" name="loc[]" value="anavilhanas"> No Parque Anavilhanas<br>
            <input type="checkbox" name="loc[]" value="jau"> No Parque Jaú<br><br>

            <input type="hidden" name="acao" value="enviar" />
            <input id="submeter" type="submit" value="Busca">
        </form>

        <div id="resultado-seg-loc"></div>
    </body>
</html>

js events.:

$(document).ready(function(){
    $("#form-seg-loc").on("submit", function(e){
        e.preventDefault();

        var dadosForm = $(this).serialize(); //nesse escopo, this é o formulário

        $.ajax({
            type: "post",
            url: "atracoes_resultados.php",
            dataType: "json",
            data: dadosForm,
            success: function (response) {
                var res = "";

                $.each(response.resultados, function(item){

                    //this é a posição atual do json
                    res += "<p>Nome 1: " + this.nome1 + "</p>" +
                        "<p>Segmento: " + this.segmento + "</p>" +
                        "<p>Nome 2: " + this.nome2 + "</p>" +
                        "<p>Localidade: " + this.localidade + "</p>" +
                        "<hr>";

                });

                $("#resultado-seg-loc").html(res);

            },
            error: function (response) {
                console.error(response);
                alert('Erro na requisição dos dados. Atualize a página');
            }
        });
        return false;
    });
});

connect_db.php:

<?php
$db = new PDO("mysql:host=localhost; dbname=SEMTUR; charset=utf8;", "USUARIO", "SENHA", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

atracoes_results.php:

<?php

require_once("connect_db.php"); //informe o caminho do arquivo caso não esteja no mesmo diretório

$seg = isSet($_POST["csg"]) ? $_POST["csg"] : null;
$loc = isSet($_POST["loc"]) ? $_POST["loc"] : null;

//caso o usuário não envie nada, pára a página
if($seg == null && $loc == null){
    exit();
}

/* MONTA A QUERY */
$optseg = "SELECT * FROM `atracoes` WHERE (";

//parte da consulta para SEGMENTO
if($seg != null){
    for($i = 0; $i < count($seg); $i++){
        $optseg .= "segmento = \"" . $seg[$i]."\"";
        if($i < count($seg)-1)
            $optseg .= " OR ";
        else
            $optseg .= ")";
    }
}

//condição para saber se é preciso adicionar um AND na consulta
if($seg != null && $loc != null){
    $optseg .= " AND (";
}

//parte da consulta para LOCALIDADE
if($loc != null){
    for($i = 0; $i < count($loc); $i++){
        $optseg .= "localidade = \"" . $loc[$i]."\"";
        if($i < count($loc)-1)
            $optseg .= " OR ";
        else
            $optseg .= ")";
    }
}

$query = $db->prepare($optseg);

$query->execute();
$resultado = $query->fetchAll(PDO::FETCH_ASSOC);

echo json_encode(
    array(
    "resultados" => $resultado
    )
);
?>

Based on the information provided this code solves the problem with some adaptations due to limitation of what could be informed.

  • I did everything as Jhonatan guided me, all right!!! Solved my problem, thanks. Stackoverflow is top!!!

Browser other questions tagged

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