PHP, как запросить все строки из таблицы базы данных - PullRequest
0 голосов
/ 27 февраля 2019

Я работаю над проектом, который включает PHP и SQL.Я должен запросить несколько столбцов в таблице.Для первых двух столбцов 'nid' и 'vid' я получил все правильные значения.Однако для последнего столбца 'title' запрос возвращает только 1-ую строку для каждого.Например, есть nids 2, 3,4 и т. Д., Но некоторые из них содержат более 1 элемента.Вместо того, чтобы возвращать заголовок для каждого элемента из 2, 3 и т. Д., Он возвращает только 1-й.Это почему?Прикрепленный снимок экрана показывает, что я говорю

$queryNodeRevision = "SELECT nid, MAX(vid) as vid, title FROM node_revision GROUP BY nid";
    // line above creates variable $queryNodeRevision > 

    $results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
    // line above creates variable $results > actually queries that database and passes in variable "$queryNodeRevision"

    while ($row = mysqli_fetch_array($results)) {
      // line above creates while loop that loops through > $row = mysqli_fetch_array($results)
      // $row is variable that's set to mysqli_fetch_array (with variable $results being passed in)
      // mysqli_fetch_array > creates an associate array for each row in a table
      // $results > variable that's being passed into associative array that represents the variable that's quering "SELECT nid FROM node_revision";
      $currentNID = $row['nid'];
      // line above creates variable that represents the current 'nid' of row (aka the key)
      // $row['nid'] = gets the key # of the current 'nid'
      $currentVID = $row['vid'];
      // line above creates variable that represents the current value of the 'vid' (the number you want to compare)
      // $row['vid'] = gets the value of the current 'vid'  
      $theTitleIWant = $row['title'];
      // line above creates variable that represents the current value of the 'title'
      // $row['title'] = gets the value of the current 'title'  
      echo "<h1>" . $row['title'] . "</h1>";
      // line prints out desired 'title' into h1 tag
    } // line closes while loop

Ниже приведена строка запроса, которая не нацелена на все заголовки правильно:

$queryNodeRevision = "SELECT nid, MAX(vid) as vid, title FROM node_revision GROUP BY nid";

Пример вывода:

enter image description here

1 Ответ

0 голосов
/ 27 февраля 2019

Для вашего ожидаемого результата нет необходимости в выражении Group by.Сделайте запрос следующим образом:

SELECT nid, (select MAX(vid) from node_revision nr1 where nr1.nid=nid) as vid, title FROM node_revision nr2 where nr2.nid=3

Надеюсь, это поможет вам

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...