PDO fetch one column from table into 1-dimensional array

前端 未结 2 996
死守一世寂寞
死守一世寂寞 2020-11-28 15:38

I\'m fairly new to PDO and getting them to work with MySQL. I seem to be getting on alright with inserting new data and retriving single results however this I am stuck with

相关标签:
2条回答
  • 2020-11-28 16:27
    <?php
    $sql = "SELECT `ingredient_name` FROM `ingredients`";
    $ingredients = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);
    
    0 讨论(0)
  • 2020-11-28 16:30

    you have to foreach or while through your fetched rows:

    foreach ($ingredient_stmt->fetchAll() as $row) {
    var_dump($row);
    }
    
    while ($row = $ingredient_stmt->fetch()) {
    var_dump($row);
    }
    

    both are kinda equivalent, foreach generates a bigger memory load as you're loading a bigger array, whereas while gets one row at a time

    notice how to use fetch and fetchAll; the former is for while, moving through each row one at a time, the latter is targeted to foreach, where the array must be known beforehand

    0 讨论(0)
提交回复
热议问题