My code:
<?php
$name = $_POST["name"];
//establishing connection through PDO
require("database.php");
try{
//querying the firstname data from the people table
$sql = $conn->query("SELECT firstname FROM people");
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
//looping through the array of firstname and echoing it out if it equals to the user input of name. else just echo out sorry no match
while($theRow = $sql->fetch(PDO::FETCH_ASSOC)){
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) && isset($_POST['name']) ){
echo $theRow['firstname'] . "<br />";
}else {
echo 'Sorry no match';
exit;
}
}
?>
the require database.php is just establishing connection to my database using PDO.
I just have 2 rows in my database with
'firstname' of
- Jack
- Bob
and if in my input field anyone types one of those 2 names php will echo out that name from the people table in the database. Very simple but the only problem I am having is on my else statement I wanted it to echo out Sorry no match if the input field of name is not equal to any name in the database. BUT instead it echo's out Sorry no match once for each name. I understand that I am looping through the array of database name but I only want it to echo Sorry no match once if the name input is not equal to a "firstname" in the database.
EXTRA NOTE:
I have also tried using a foreach loop instead of the while looping with the fetchAll method instead of just fetch but no luck there. Basically gave me the same results.
UPDATE ON THE PROBLEM:
When I load the page the else statement is already taking effect and echoing out Sorry no match even before I set a name in the input. and if I type the wrong name it ill echo out Sorry no match twice if I type the correct name it will echo out the name out of the database and Sorry no match once.
FIGURED IT OUT:
<?php
$name = $_POST["name"];
require("database.php");
try{
$sql = $conn->prepare("SELECT firstname FROM people WHERE firstname = ?");
$sql->bindParam(1,$name);
$sql->execute();
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
$theRow = $sql->fetch(PDO::FETCH_ASSOC);
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
echo $theRow['firstname'] . "<br />";
}else{
echo 'no match';
}
?>
Turns out I did not even need a loop do to the WHERE claus only getting the firstname that matched $_POST['name'] so it was just a matter of when to out put that data and that was when the if statement came in. But if I had to output more than one single data I would of probably used a foreach loop like so:
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
foreach( $theRow as $row ){
echo $row . "<br />";
}
}else{
echo 'no match';
}
If anyone sees any problem with this code or my method please do let me know. Thank you