【发布时间】:2015-05-20 23:29:21
【问题描述】:
我的代码:
<?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;
}
}
?>
require database.php 只是使用 PDO 建立与我的数据库的连接。
我的数据库中只有 2 行
的“名字”
- 杰克
- 鲍勃
如果在我的输入字段中任何人键入这两个名称之一,php 将从数据库中的人员表中回显该名称。非常简单,但我遇到的唯一问题是在我的 else 语句中,如果 name 的输入字段不等于数据库中的任何名称,我希望它回显 Sorry no match。但相反,它回显了对不起,每个名字都没有匹配一次。我知道我正在遍历数据库名称数组,但如果名称输入不等于数据库中的“名字”,我只希望它回显一次 对不起,不匹配。
额外说明:
我也尝试过使用 foreach 循环,而不是使用 fetchAll 方法的 while 循环,而不是仅仅 fetch 但没有运气。基本上给了我同样的结果。
问题更新:
当我加载页面时,else 语句已经生效并且 甚至在我在输入中设置名称之前就回显抱歉没有匹配。 如果我输入了错误的名称,它会回显 Sorry no match 两次,如果 我输入正确的名称,它将从数据库中回显该名称 对不起,没有匹配一次。
想通了:
<?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';
}
?>
事实证明,我什至不需要对 WHERE 子句进行循环,只获取与 $_POST['name'] 匹配的名字,所以这只是何时输出该数据的问题,那就是 if 语句进来了。但是如果我必须输出多个数据,我可能会使用这样的 foreach 循环:
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
foreach( $theRow as $row ){
echo $row . "<br />";
}
}else{
echo 'no match';
}
如果有人发现此代码或我的方法有任何问题,请告诉我。谢谢
【问题讨论】:
-
尝试使用break;而不是退出;
-
不走运,但我更新了我的问题,以便更好地了解问题所在
标签: php mysql database if-statement pdo