0

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 statement to fetch all of the rows containing a position_id in the array. I'm trying to use this data to fill a dropdown menu.

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

// $_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);

}
Moose
  • 1
  • 2
  • Your script is vulnerable to [SQL Injection Attack](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even if [you are escaping variables, its not safe](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string%5D)! You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either MYSQLI or PDO instead of concatenating user provided values into the query. – Barmar Jun 02 '22 at 00:57

0 Answers0