1

I have three links each with an 'ORDER BY' option. I used this if structure to change the $sql and order it in the right way. I don't get any errors on my order pages but on the main, unsorted page I get "Notice: Undefined index: sort" on each line where I use sort (3 times).

I googled and tried a few of the possible solutions on stackoverflow but nothing helped so far. I'm sorry if this is a basic question but I'm quite new to php so I'm a bit confused as to why I'm getting this error.

<?php

//Query for speaker information
$sqlOverzichtSprekers = "SELECT idsprekers, voornaam, naam, afbeelding, 
bio, likecounter FROM sprekers";

//Sql ORDER BY
if ($_GET['sort'] == 'alpha')
{
    $sqlOverzichtSprekers .= " ORDER BY voornaam DESC";
}
elseif ($_GET['sort'] == 'popular')
{
    $sqlOverzichtSprekers .= " ORDER BY idsprekers";
}
elseif ($_GET['sort'] == 'likes')
{
    $sqlOverzichtSprekers .= " ORDER BY likecounter DESC";
}

//Query for speaker
if(!$resOverzichtSprekers = $mysqli->query($sqlOverzichtSprekers)){
    echo "Oeps, een query foutje op DB voor opzoeken sprekers";
    print("<p>Error: " . $mysqli->error . "</p>");
    exit();
}

?>

The order by/sort pages work fine without any errors, only the main unsorted page has the following error: Notice: Undefined index: sort.

maximst96
  • 23
  • 2
  • 1
    in the url that loads this page is there `?sort= ..` `$_GET['sort']` means that you have that variable come from the url, looks like its not –  Jun 05 '19 at 21:30

1 Answers1

1

As you said the main unsorted page has a problem... that is because there is nothing sent as $_GET['sort'] but you are blindly trying to read it. Hence the error.

First see if the $_GET['sort'] has a value or not, then use it. Even better, assign it to a variable and then use it... like this:

$sort = (isset($_GET['sort']) == true) ? $_GET['sort'] : '';

//Query for speaker information
$sqlOverzichtSprekers = "SELECT idsprekers, voornaam, naam, afbeelding, 
bio, likecounter FROM sprekers";

//Sql ORDER BY
if ($sort == 'alpha')
{
    $sqlOverzichtSprekers .= " ORDER BY voornaam DESC";
}
elseif ($sort == 'popular')
{
    $sqlOverzichtSprekers .= " ORDER BY idsprekers";
}
elseif ($sort == 'likes')
{
    $sqlOverzichtSprekers .= " ORDER BY likecounter DESC";
}
Nawed Khan
  • 4,393
  • 1
  • 10
  • 22