Error Object of class stdClass could not be converted to string

Asked

Viewed 11,463 times

4

Well I have an 'X' object that one of its properties is a JSON. In this JSON contains the column name and the column value respectively.

But I can have several 'X' objects, and so on. Today I’m dazzling like this:

PHP:

 public function SincronizaBanco_MobileWeb(array $params = NULL) {
    $objeto = json_decode($this->params['objJSON']);
    $tamanho = count($objeto);

    try {
        for ($i = 0; $i < $tamanho; $i++) {
            if ($objeto[$i]->FLG_IDENT_OPERA == 'I') {
                $inputs = array();
                $inputsJSON = $objeto[$i]->TXT_COLUN_SINCR;
                $inputs[':values'] = json_decode($inputsJSON);

                print_r($inputs);

                $sincronismo = $this->conexao->save("INSERT INTO " + $objeto[$i]->TXT_TABLE_SINCR + " values (:values);", $inputs);
            } else if ($objeto[$i]->FLG_IDENT_OPERA == 'U') {

            } else {

            }
        }
        print_r("Inserção concluido com sucesso !");
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}
}

You’re making the following mistake:

[Sat Dec 05 09:22:57 2015] [error] [client 192.168.1.248] PHP Catchable fatal error: Object of class stdClass could not be converted to string in /opt/lampp/htdocs/Renan/conexion.php on line 53, referer: http://127.0.0.1:58889/

The error occurs in the following function:

    public function execute(PDOStatement $stmt, array $data = null) {
    try {
        if (isset($data)) {
            $stmt->execute($data);
        } else {
            $stmt->execute();
        }
    } catch (PDOException $exc) {
        echo $exc->getTraceAsString();
        var_dump($exc->getMessage());
    }
}

And what you call this function is

    public function save($sql, array $data) {

    $con = self::getConnection();

    $stmt = $con->prepare($sql);
    print_r($stmt);
    $this->execute($stmt, $data);

    if ($stmt->rowCount()) {
        return true;
    } else {
        return false;
    }
}

How do I fix this ?

My array after json_decode is like this:

    Array
(
    [0] => stdClass Object
        (
            [COD_IDENT_SINCR] => 1
            [TXT_TABLE_SINCR] => tbl_PESSOAS
            [FLG_IDENT_OPERA] => I
            [TXT_COLUN_SINCR] => {"COD_IDENT_PESSO":"1151205091356692","TXT_NOMEX_PESSO":"iyuiyui","TXT_APELI_PESSO":"yuiyuiy","FLG_SEXOX_PESSO":"","DAT_NASCI_PESSO":"","TXT_NASCI_PESSO":"","TXT_NATUR_PESSO":"","FLG_ESTAD_CIVIL":"S","TXT_FONEX_PESSO":"","FLG_IDENT_PESSO":"A","TXT_EMAIL_PESSO":"","TXT_SENHA_PESSO":"","TXT_ENDER_CEPXX":"","TXT_ENDER_LOGRA":"","TXT_ENDER_BAIRR":"","TXT_ENDER_NUMER":"","TXT_ENDER_COMPL":""}
            [TXT_WHERE_SINCR] => 
            [FLG_IDENT_SINCR] => N
            [COD_IDULT_ATUAL] => -1
            [DAT_ULTIM_ATUAL] => 2015-11-05 09:13:56
        )

    [1] => stdClass Object
        (
            [COD_IDENT_SINCR] => 2
            [TXT_TABLE_SINCR] => tbl_PESSOA_TURMA
            [FLG_IDENT_OPERA] => I
            [TXT_COLUN_SINCR] => {"COD_IDENT_PESSO":"1151205091356692","COD_IDENT_CELUL":"1","FLG_IDENT_PESSO":"M","COD_IDULT_ATUAL":"-1","DAT_ULTIM_ATUAL":"2015-11-05 09:13:56"}
            [TXT_WHERE_SINCR] => 
            [FLG_IDENT_SINCR] => N
            [COD_IDULT_ATUAL] => -1
            [DAT_ULTIM_ATUAL] => 2015-11-05 09:13:56
        )

)
  • Why did you create another method execute where the PDO itself already carries one with it ? And $data is an instance of array ?

  • Puts the full script on Pastebin along with the file json.

  • I don’t understand Edilson

  • You created another method execute, where the PDO itself already carries one. And you are declaring types for the arguments.

  • But the problem is not there, I need this, to have security in which part of the code is.

  • Whatever. I also asked you to show the rest of the script. And rename your method execute for something else.

  • However I know where the problem is... The error comes because I need to define an array of objects and I need to save it. The rest is file. Help me in this matter.

  • The php script ?

  • Because everything that involves in this error is posted there.

  • I updated the question, see her

  • Seen this way, the problem seems to be in the first loop for, where you build the array that contains the values. I’ll analyze them better, reply as soon as I can.

  • Look the problem is even in how you mount the array to insert. From the column [TXT_COLUN_SINCR] What values do you want to enter ? Only one or all in the same field of the database ?

  • I need to insert all, these values are related to the values you have there in the table.

  • COD_IDENT_PESSO and the other indices are table fields ?

  • Yes, they are all table fields

  • 3

    It was that question, fortunately the answer below already answered that.

Show 11 more comments

1 answer

2


Catchable fatal error: Object of class stdClass could not be converted to string in

The error happens when you try to manipulate a composite type(array or object) in a string or try to print some of them with print or echo.

save() takes a string(SQL command) and tries to execute the operation in the database, but the symbol for concatenating strings is . and not +

$sincronismo = $this->conexao->save("INSERT INTO " + $objeto[$i]->TXT_TABLE_SINCR + " values (:values);", $inputs);

I would rewrite the logic of the method to simplify some things and make others clearer.

Would exchange the for convectional by a foreach to eliminate the vailable $tamanho and exchange inputs $objeto[$i]->algo for $item->algo.

Maybe it wasn’t clear in the question but TXT_COLUN_SINCR seems to be the record to be saved in the database however it is as a json so it is necessary to convert it its structure gets like this:

Array
(
    [COD_IDENT_PESSO] => 1151205091356692
    [TXT_NOMEX_PESSO] => iyuiyui
    [TXT_APELI_PESSO] => yuiyuiy
    [FLG_SEXOX_PESSO] => 
    [DAT_NASCI_PESSO] => 
    [TXT_NASCI_PESSO] => 
    [TXT_NATUR_PESSO] => 
    [FLG_ESTAD_CIVIL] => S
    [TXT_FONEX_PESSO] => 
    [FLG_IDENT_PESSO] => A
    [TXT_EMAIL_PESSO] => 
    [TXT_SENHA_PESSO] => 
    [TXT_ENDER_CEPXX] => 
    [TXT_ENDER_LOGRA] => 
    [TXT_ENDER_BAIRR] => 
    [TXT_ENDER_NUMER] => 
    [TXT_ENDER_COMPL] => 
)

The idea is basically to assemble the query correctly, first json_decode() in $item->TXT_COLUN_SINCR to return the above array, from it mount the list of fields and Binds with the instruction: $campos = implode(',', array_keys($json)); what changes is the list of Binds has : before the name fields.

With the list of fields and Binds ready just put them in the string that contains SQL, with sprintf(), each %s is replaced by each value in the order, the first places the table name, the second the field list and the last the Binds.

public function SincronizaBanco_MobileWeb(array $params = NULL) {
    $objeto = json_decode($this->params['objJSON']);
    try{
        foreach($objeto as $item){
            if($item->FLG_IDENT_OPERA == 'I'){
                $json = json_decode($item->TXT_COLUN_SINCR, true);
                $campos = implode(',', array_keys($json));
                $binds = ':'. implode(',:', array_keys($json));

                $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $item->TXT_TABLE_SINCR, $campos, $binds);
                $sincronismo = $this->conexao->save($sql, $json);

            } else if ($objeto[$i]->FLG_IDENT_OPERA == 'U') {
            }else{
            }
        }
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}

Another alternative to the second implode() is the use of str_replace() to remove the :.

$binds = ':'. implode(',:', array_keys($json));
$campos = str_replace(':', '', $binds);
  • In case friend how would be the update ? I’m trying to make here always give the same error Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near And the problem is in my SQL

Browser other questions tagged

You are not signed in. Login or sign up in order to post.