PHP

时间:2016-01-14 04:56:15

标签: php pdo

我正在尝试使用PDO LIKE查询显示记录,但我收到此错误消息我可以知道如何解决此问题。

这是我的代码:

 $rs = new JSONRecordSet();
 $searchbooksSQL = "SELECT Title FROM l_stock WHERE Title LIKE ?";
 $params = array("%$term%");
 echo $rs->getRecordSet($searchbooksSQL, $params);

这是getRecordSet代码:

class R_RecordSet {
    function getRecordSet($sql, $params = null) {
        if (is_array($params)) {
            $this->stmt = $this->db->prepare($sql);
            // execute the statement passing in the named placeholder and the value it'll have
            $this->stmt->execute($params);
        } else {
            $this->stmt = $this->db->query($sql);
        }
        return $this->stmt;
    }
}

class JSONRecordSet extends R_RecordSet {
    function getRecordSet($sql, $elementName = "ResultSet", $params = null) {
        $stmt = parent::getRecordSet($sql, $params);
        $recordSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $nRecords = count($recordSet);
        if ($nRecords == 0) {
            $status = 'error';
            $message = json_encode(array("text" => "No records found"));
            $result = '[]';
        } else {
            $status = 'ok';
            $message = json_encode(array("text" => ""));
            $result = json_encode($recordSet);
        }
        return "{\"status\": \"$status\", \"message\":$message, \"$elementName\" :{\"RowCount\": $nRecords ,\"Result\": $result}}";
    }
}

我得到的错误消息是“注意:数组到字符串转换”

1 个答案:

答案 0 :(得分:2)

getRecordSet()定义为:

function getRecordSet($sql, $elementName = "ResultSet", $params = null) {

但是,您将其称为:

echo $rs->getRecordSet($searchbooksSQL, $params);

您需要修改代码以传入适当的$elementName参数。 (默认值可能合理。)

 echo $rs->getRecordSet($searchbooksSQL, 'ResultSet', $params);


此外,您应该使用json_encode()JSONRecordSet::getRecordSet()生成最终结果,而不是使用字符串连接来构建它。它将使代码更易于阅读和理解。

此外,由于输入参数的语义发生了变化,getRecordSet()的{​​{1}}的两个实现彼此不兼容,很可能导致参数不匹配在您的呼叫站点首先。您可能希望将JSONRecordSet::getRecordSet()参数重新排序为:

function getRecordSet($sql, $params = null, $elementName = 'ResultSet') {