0

Is there a way for me to change this MYSQL statement

$query = "SELECT Monsters.ID AS `mID`, 
          Monsters.Name AS `MName`, Monsters.MonsterType_ID, 
          MonsterType.Name FROM Monsters ";
$query .= "inner join MonsterType ON Monsters.MonsterType_ID = MonsterType.ID 
          ORDER BY MonsterType.Name ASC";
 $result = $mysqli->query($query);

if ($result && $result->num_rows > 0) {
echo "<div class='row'>";
echo "<center>";
echo "<h2>The Monster Database</h2>";
echo "<table>";
echo "<tr><th>Name</th><th>Type</th>
<th></th><th></th></tr>";
while ($row = $result->fetch_assoc())  {
    echo "<tr>";    
    //Output FirstName and LastName
    echo "<td>" .$row["MName"]."</td>";
    echo "<td>" .$row["Name"]."</td>";

such that this image Monster Database Names and Types is ordered as it is by Type, but the Monster Names associated with that type are also alphabetized? So for the Beast Type, it'd be listed as

Boar         Beast

Grizzly Bear Beast

Panther      Beast

Polar Bear   Beast

Titanoboa    Beast

Wolf         Beast

Thank you!

EDIT: Solution was MonsterType.Name ASC, MName ASC. Thank you everyone!

  • what result does it currently produce? – Andrew Apr 26 '18 at 19:12
  • I linked an image showing the current results. However, someone commented the solution and then deleted it. But it does what I want: ORDER BY MonsterType.Name ASC, MName ASC; – Connor Brown Apr 26 '18 at 19:17
  • FYI, ASC is not necessary as that is the default sort order. It doesn't hurt anything to include it, but it will work just the same without it. – Don't Panic Apr 26 '18 at 19:21

2 Answers2

1

This should work:

$query = "SELECT Monsters.ID AS `mID`, 
  Monsters.Name AS `MName`, Monsters.MonsterType_ID, 
  MonsterType.Name FROM Monsters ";
$query .= "inner join MonsterType ON Monsters.MonsterType_ID = 
  MonsterType.ID ORDER BY MonsterType.Name ASC, MName ASC";
jonasfh
  • 4,151
  • 2
  • 21
  • 37
1

Change your order by statement to include the monsters name after the monster type.

$query = "SELECT Monsters.ID AS `mID`   , 
          Monsters.Name       AS `MName` , 
          Monsters.MonsterType_ID        , 
          MonsterType.Name FROM Monsters 
        INNER JOIN MonsterType ON Monsters.MonsterType_ID = MonsterType.ID 
          ORDER BY MonsterType.Name,Monsters.Name ASC";
Dave
  • 5,108
  • 16
  • 30
  • 40