Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

?
Lv 5

PHP database query?

Hello,

I am working with very limited knowledge of html for a personal page, so I do apologize for the simplicity of my question.

I'm trying to implement a search function on my page. The search word will be searched for in the respective column of the db file and show results of the row, else say "Not Found." I've managed to create a db file (database.db) with 'Name', 'X' and 'Y' fields.

When I run the script below without the if-else function, it will return the relevant fields correctly. I wanted the added function of displaying "Not Found" if there is no match, but I can't seem to get it to work. The current code below returns Parse error: syntax error, unexpected 'else' (T_ELSE). Am I missing something? Assuming I can fix the error, is my if-else statement even correct for my purposes to begin with?

Thank you for any help in advance.

<?php

//load database connection

$myPDO = new PDO('sqlite:database.db');

// Search from SQL database table

$search=$_POST['search'];

$query = $myPDO->prepare("select * from Directory where Name LIKE '$search'");

$query->execute();

$results = $query->fetchAll(PDO::FETCH_ASSOC);

if (count($results) > 0){

Foreach ($results as $row){

echo $row['Name'];

echo "<br>";

echo $row['X'];

echo "<br>";

echo $row['Y'];

} else {

echo 'Not Found';}

?>

3 Answers

Relevance
  • Chris
    Lv 7
    4 years ago
    Favorite Answer

    You have a } that closes the foreach loop, then the "else". You need an additional } to close the if-block.

    echo $row['Y'];

    } // end foreach

    } else {

    I recommend using an IDE like Netbeans, it would have pointed out the error as you typed.

  • ?
    Lv 5
    4 years ago

    Perfect! Thank you very much

  • 4 years ago

    why not just practice at the proper place the w3schools.com you can try out code there

Still have questions? Get your answers by asking now.