PHP检查是否使用PDO查询远程数据库返回的数据

时间:2014-03-31 00:56:19

标签: php mysql pdo

以下代码用于检查某个查询是否返回数据。该查询获取用户在另一页上搜索的一段会话数据。

$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中执行此操作,因为查询符合相同的标准。我想象的fetch行方法在这种情况下不是最理想的,所以有没有更好的方法来查看查询是否返回任何内容?

1 个答案:

答案 0 :(得分:1)

一些事情。当前查询不是SQL安全的。 $_SESSION['assignment_searched']可能包含恶意值,因此我建议使用PDO Quote函数或使用预准备语句。在下面的例子中,我使用了预备语句。

准备好并执行查询后,您可以轻松检查返回的行数并循环显示。

在互联网上有很多有用的PDO示例。在Google中快速搜索会有所帮助。 PDO的PHP手册也非常好,社区提供了很多例子。

https://www.google.com/search?q=PHP+PDO+MySQL+Examples

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);
    }
}