1

What I am trying to achieve is make a page where there is an alphabet and when you click on a letter in the alphabet, you will get the value thats in the column in the database.

An example if you didn't understand it.

Database:

John
Jason
Jos
Jan
Marco
Bott

So I click on a letter in the alphabet:

<a href="?tag=J">J</a>

This should give me all the users starting with J.

This is my code which doesnt work (it always returns too else).

            if(isset($_GET['tag'])){
                $tag = $_GET['tag'];
                $check = range('A', 'Z');
                foreach($check as $row){
                    if($tag == $row){
                        $query = $pdo->prepare("SELECT names FROM users WHERE UPPER(names) LIKE '{$row}%'");
                    } else {
                        $query = $pdo->prepare("SELECT names FROM users");
                    }
                }
            }
Efekan
  • 1,497
  • 12
  • 31

1 Answers1

1

Quick bugfix.

if(isset($_GET['tag'])){
    $tag = $_GET['tag'];
    $check = range('A', 'Z');
    // default query
    $query = $pdo->prepare("SELECT names FROM users");
    foreach($check as $row){
        if($tag == $row){
            $query = $pdo->prepare("SELECT names FROM users WHERE UPPER(names) LIKE '{$row}%'");
            // do not check other
            break; 
        } 
    }
}

But it is wrong way. You do not need foreach.

if(isset($_GET['tag'])){
    $tag = $_GET['tag'];
    if (preg_match('/^[A-Z]/', $tag, $matches)){
            $query = $pdo->prepare("SELECT names FROM users WHERE UPPER(names) LIKE '{$matches[0]}%'");
        } else {
            $query = $pdo->prepare("SELECT names FROM users");
        }
}
sectus
  • 15,605
  • 5
  • 55
  • 97