简体   繁体   中英

Array to string conversion notice in PHP

I am trying to display records using PDO LIKE query, but I am getting this error message can I know how to solve this.

This is my code:

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

This is the getRecordSet code:

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

The error message i am getting is "Notice: Array to string conversion"

getRecordSet() is defined as:

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

however, you are calling it as:

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

You will need to modify your code to pass in an appropriate $elementName parameter. (The default is probably reasonable.)

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


Additionally, you should probably use json_encode() to generate the final result from JSONRecordSet::getRecordSet() , rather than building it up with string concatenation. It will make the code easier to read and understand.

Also, your two implementations of getRecordSet() are incompatible with each other, according to the Liskov Substitution Principle due to the change in the semantics of the input parameters, and is likely what led you to the parameter mismatch at your call site in the first place. You probably want to re-order JSONRecordSet::getRecordSet() parameters to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM