首页 > 解决方案 > PHP 准备对象查询不返回任何数据

问题描述

我有一些 PHP 代码将发布请求作为准备好的语句的输入。它不返回任何信息。没有错误。

我尝试对传递给准备好的对象的变量进行硬编码,但无济于事。

如果我使用所需的查询手动查询数据库,则会收到输出。

我在这里想念什么?我该怎么做才能获得输出?

这是我的代码:

<?php

$username = "user";
$password = "ultrasecurepassword";

try {
    $pdo = new PDO('mysql:unix_socket=/run/mysql/mysql.sock;dbname=news', $username, $password);

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$query = "SELECT * FROM newsdb ORDER BY pubdate DESC LIMIT 250";
if(!empty($_POST['search'])){
    $termobusca = htmlspecialchars($_POST['search']);
    $tipobusca = htmlspecialchars($_POST['searchtype']);

    if($tipobusca == "title"){
        $stmt = $pdo->prepare("SELECT * from newsdb where title like '%:term%' ORDER BY pubdate DESC limit 5000;");
    }
    else {
        $stmt = $pdo->prepare("SELECT * from newsdb where pubdate like '%:term%' ORDER BY pubdate DESC limit 5000;");
    }

    $stmt->bindParam(1, $termobusca);

}
else {
    $stmt = $pdo->prepare("SELECT * FROM newsdb ORDER BY pubdate DESC LIMIT 250");
}


$stmt->execute();

while($row = $stmt->fetch()){
    print_r($row);
}


$pdo = null;
?>

标签: phpmysqlpdo

解决方案


我已经看到这个问题之前以某种方式尝试这个请

if($tipobusca == "title"){
    $stmt = $pdo->prepare("SELECT * from newsdb where title like :term ORDER BY pubdate DESC limit 5000;");
}
else {
    $stmt = $pdo->prepare("SELECT * from newsdb where pubdate like :term ORDER BY pubdate DESC limit 5000;");
}
$term  = '%'.$termobusca.'%';
$stmt->bindParam(':term', $term, PDO::PARAM_STR);

推荐阅读