下面的代码用于检查某个查询是否返回数据。该查询获取用户在另一个页面上搜索的会话数据。
$whatwechecking = $_SESSION ['assignment_searched'];
$FindAsigns = $connection->query("SELECT `NAME`,`DATE`,`GRADE` FROM grades
WHERE `ASSIGNMENT` = '$whatwechecking' ORDER BY `ASSIGN_ID` DESC LIMIT 0,5");
if ($FindAsigns->fetchColumn() > 0) //this is the attempt at seeing if
//the query returned something
{
while($row = $FindAssigns->fetch()) //this loop outputs the data found in the
//query into a table
{
...find data
echo (...echo out data into table);
}
}
else
{
header('Location: NameNotFound.php'); //this is to redirect the user
to an error page that says data was not retreived in the query
}
理想情况下,我想在PDO中这样做,因为查询是在相同的标准。我认为在这种情况下,获取行方法不是最理想的,那么是否有更好的方法来查看查询是否没有返回任何内容?
有几点。当前查询不是sql安全的。$_SESSION['assignment_searched']
可能包含恶意值,因此我建议使用PDO Quote函数或使用准备好的语句。在下面的例子中,我使用了预处理语句。
一旦你准备好并执行了查询,你就可以很容易地检查返回了多少行并循环它们。
在互联网上有很多有用的PDO的例子。在谷歌上快速搜索一下会有帮助。关于PDO的PHP手册也非常好,社区贡献了许多示例。 https://www.google.com/search?q=PHP + PDO + MySQL +例子http://www.php.net/manual/en/book.pdo.php// Create PDO Prepared Statement (leave placeholder for our variable)
$stmt = $connection->prepare("
SELECT `NAME`, `DATE`, `GRADE` FROM grades
WHERE `ASSIGNMENT` = :whatwechecking
ORDER BY `ASSIGN_ID` DESC
LIMIT 0,5
");
// Bind Data to Placeholder in Statement and Execute (SQL-safe)
$stmt->execute(array('whatwechecking' => $_SESSION['assignment_searched']));
// Check if Anything was returned
if ($stmt->rowCount() > 0) {
// YES! Fetch Items and Loop Through
foreach ($stmt->fetchAll() as $item) {
var_dump($item);
}
}