如何从mysql查询顺序推入数组?

k2fxgqgv  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(346)

php和js如下所示:

createRoomTable()

    function createRoomTable(){
      $.post('../include/returnRoomTable.php',{
        //nothing to transmit
      }).then((returnedTableMarkup) => {
        returnedTableMarkup = JSON.parse(returnedTableMarkup)
        console.log("data from returnRoomTable.php is ", returnedTableMarkup)
        //$('#roomTableOutput').html(returnedTableMarkup)
      })
    }
<?php
session_start();

try{
  $connection = new PDO('mysql:host=localhost;dbname=XXXX',
  'XXXX','XXXXXX');
}catch(PDOException $e){
  echo $e->getMessage();
}

$allRooms = $connection->query("
SELECT name
FROM raum
")->fetchAll(PDO::FETCH_NUM);

$indexLimit = count($allRooms);
$allSeats = [];
for($index = 0; $index < $indexLimit; $index++){
  $allSeats =  array_push($connection->query("
  SELECT nummer
  FROM arbeitsplatz
  WHERE raum = '".$allRooms[$index]."'
  ")->fetchAll(PDO::FETCH_NUM));
}

echo json_encode ($allSeats);

?>

所以目前,consolelog说数组是“空的”。我需要的是一个灵活的二维数组(“$allseats”),它从mysql查询获取每个迭代并将其放入这个数组中。问题是我对php中的数组没有太多经验,我不知道如何实现这一点。

wnrlj8wa

wnrlj8wa1#

好吧,我自己找到了解决问题的办法:
php现在如下所示:

<?php
session_start();

try{
  $connection = new PDO('mysql:host=localhost;dbname=arbeitsplatzverwaltung',
  'verwalter','N7pY1OTl2gaBbc51');
}catch(PDOException $e){
  echo $e->getMessage();
}

$allRooms = $connection->query("
SELECT name
FROM raum
")->fetchAll(PDO::FETCH_NUM);

$indexLimit = count($allRooms);
$allSeats = [];

for($index = 0; $index < $indexLimit; $index++){
  $currentQuery = $connection->query("
  SELECT nummer
  FROM arbeitsplatz
  WHERE raum = '".$allRooms[$index][0]."'
  ")->fetchAll(PDO::FETCH_NUM);

  array_push($allSeats, $currentQuery);
}
/*
$allSeats[] = $connection->query("
 SELECT nummer
 FROM arbeitsplatz WHERE raum = '".$allRooms[$index]."'
 ")->fetchAll(PDO::FETCH_NUM);*/

echo json_encode ($allSeats);

?>

当我在js中输出这个值时,我得到一个包含这些值的数组。

相关问题