简体   繁体   中英

Php pdo foreach

Here I have php pdo function to get json from database

try {
      $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

     $result = $conn->prepare("SELECT id_tabele,naziv FROM track_aktivnosti WHERE prvi=:prvi AND id_akt=:id_akt AND tabela=:tabela");
     $result->execute(array(':prvi' => $_POST['prvi'], ':id_akt' => $_POST['id_akt'], ':tabela' => $_POST['tabela']));
    $result = $result->fetchAll(); 

          foreach($result as $r) {
          $temp = array();
          $temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']); 

        }
    $table = $temp;
    $jsonTable = json_encode($table);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;

but I get just one result, one element in json etc.

[{"id":1,"ime_prezime":"Pera Peric"}] 

other element I can't get. WHY?

I must get json like this:

[{"id":1,"ime_prezime":"Pera Peric"},[{"id":2,"ime_prezime":"Laza Lazic"}] ] 

but I get only 1.st element and other not ...

You are overwriting the array inside the foreach on each iteration. This essentially means that the array is emptied on each iteration. The array will only contain the values from the last iteration. Move the $temp = array(); declaration outside the loop to fix this:

$temp = array(); // intialize the array

foreach($result as $r) {
    $temp[] = array(
        'id' => (int) $r['id_tabele'], 
        'ime_prezime' => (string) $r['naziv']
    ); 
}

The above fix will make your code work, but I recommend using the approach using SQL aliases as shown in @YourCommonSense 's answer below.

You are doing a whole lot of useless operations. It's no wonder why you got lost.

$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);

$sql = "SELECT id_tabele id, naziv ime_prezime FROM track_aktivnosti 
        WHERE prvi=? AND id_akt=? AND tabela=?";

$stmt = $conn->prepare($sql);
$stmt->execute(array($_POST['prvi'], $_POST['id_akt'], $_POST['tabela']));
echo json_encode($result->fetchAll()); 

declare

$temp = array(); 

out side the loop since you have this inside the loop and on each iteration its declared as new array and previous entries are wiped.

ie

$temp = array();
foreach($result as $r) {

          $temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']); 

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM