-1

Here is a screenshot of database records ( don't mind weird entries, they are for testing) http://i42.tinypic.com/9uumpc.png

But when I run following query no matter what, upper/lower/quotes/double quotes it returns empty.

SELECT * FROM BusDetails WHERE category='$cat'

$cat = "Accountants"

it doesn't return anything. Even though there is a record with such category. And I know its not my PHP fault, I tried running this query in myadmin SQL.

4

1 回答 1

2

为了学习最佳实践,这里有一个使用 PDO(PHP 数据对象)与数据库交互的示例。

//Make a connection to your database.
$dbh = new PDO('mysql:host=localhost;dbname=<YOURDB>', '<USERNAME>', '<PASSWORD>');

$cat = "Accountants";
$STH = $dbh->prepare("SELECT * FROM BusDetails WHERE category = :cat");
$STH->bindParam(":cat", $cat); //This binds your parameter and replaces :cat 
                               //with the value of $cat escaped

$STH->setFetchMode(PDO::FETCH_ASSOC);
$STH->execute();

while($row = $STH->fetch()) {
    //interact with results here
}

这将允许您执行您提供的查询以及转义任何可能导致注入的字符(请参阅 Bobby 表)。如果 $cat 曾经被分配给用户给定的值(即搜索词),则此代码将按原样工作。

如果您的查询增长到需要额外的参数(我假设他们会这样做),您可以简单地在查询中添加额外的 :param 占位符并使用 bindParam 方法绑定值,如图所示。

于 2013-06-11T18:37:24.890 回答