Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

287
Visualizações
Using PDO fetch to get an array of parameters for second PDO fetch

I'm trying to fetch all of the position_id's in order to fill an array which I can then pass to the second SQL statement's WHERE clause to fetch all of the rows containing a position_id from that array. I'm trying to use this data to fill a dropdown menu.

TLDR: First fetch gets an array of parameters for the WHERE clause in the second statement.

Expected result: JSON encoded string which I can then parse for my dropdown menu.

Actual result: Uncaught SyntaxError: Unexpected token < in JSON at position 0

Am I doing this properly or is there a better way to do this?

PHP:

// $_POST['aid'] == election_id
if(isset($_POST['aid'])) {
    // Get's the rows with corresponding election_id 
    $stm = $db->prepare("SELECT * FROM position_elections WHERE election_id = " . $_POST['aid']);
    $stm->execute();
    $position_ids = [];
    if ($row = $stm->fetchAll(PDO::FETCH_ASSOC)) 
    {
        $position_id = $row['position_id'];
        array_push($position_ids, $position_id);
    }

    $ids = join("','",$position_ids);
    $stm2 = $db->prepare("SELECT * FROM positions WHERE position_id IN ($ids)");
    $stm2->execute();
    $positions = $stm2->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($positions);

}

HTML/JavaScript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#elections").change(function(){
            // election id
            var aid = $("#elections").val();
            $.ajax({
                url: '../assets/php/request_candidacy.data.php',
                method: 'post',
                data: 'aid=' + aid
            }).done(function(positions){
                console.log(positions);
                positions = JSON.parse(positions);
                positions.forEach(function(positions){
                    $('#positions').append('<option>' + positions.name + '</option>')
                })
            })
        })
    })
</script>
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda