使用bindParam显示数据库中的数据

时间:2017-12-31 02:16:38

标签: php mysql bindparam

我想尝试使用bindParam从数据库显示我的数据,但是我收到了一些错误。

  

可恢复的致命错误:第15行的C:\ xampp \ htdocs \ piratefiles \ search.php中无法将类PDOStatement的对象转换为字符串

这里是我的代码

$category = htmlentities($_GET['c']);
$query = htmlentities($_GET['q']);

$page = (isset($_GET['page'])) ? $_GET['page'] : 1;
$limit = 20;
$limit_start = ($page - 1) * $limit;

$query = $db->prepare ("SELECT * FROM `posting` WHERE 'category' = :category AND 'file_name' like :query ORDER BY date DESC LIMIT ".$limit_start.",".$limit);

$query->bindParam(":category", $category);
$query->bindParam(":query", $query);

$query->execute();

2 个答案:

答案 0 :(得分:4)

$query是用户输入,然后您将其指定为PDOStatement,然后将其传递回bindParam

更改var名称。

$category = htmlentities($_GET['c']);
$query = htmlentities($_GET['q']);

$page = (isset($_GET['page'])) ? $_GET['page'] : 1;
$limit = 20;
$limit_start = ($page - 1) * $limit;

$stmt = $db->prepare ("SELECT * FROM `posting` WHERE 'category' = :category AND 'file_name' like :query ORDER BY date DESC LIMIT ".$limit_start.",".$limit);

$stmt->bindParam(":category", $category);
$stmt->bindParam(":query", $query);

$stmt->execute();

答案 1 :(得分:0)

因为即时使用LIKE,所以需要制作另一个变量。

$keyword1 = "%".$category."%";
$keyword2 = "%".$query1."%";

这是完整的代码。

$category = htmlentities($_GET['c']);
$query1 = htmlentities($_GET['q']);

$page = (isset($_GET['page'])) ? $_GET['page'] : 1;
$limit = 20;
$limit_start = ($page - 1) * $limit;

$query = $db->prepare ("SELECT * FROM `posting` WHERE category LIKE :category AND file_name LIKE :query1 ORDER BY date DESC LIMIT ".$limit_start.",".$limit);

$keyword1 = "%".$category."%";
$keyword2 = "%".$query1."%";

$query->bindParam(":category", $keyword1);
$query->bindParam(":query1", $keyword2);

$query->execute();