Bank insertion error Object of class PDOStatement could not be converted to string

-2

I'm trying to insert some data into a table using PHP and some errors are happening.

This is the way I'm using to insert:

$cnpj = "000001";
$sth = $lokos->prepare("INSERT INTO CLENTES (CNPJ) VALUES (?)"); 
$sth->bindParam(1, $cnpj, PDO::PARAM_STR);
$sth->execute(); 
$result = $sth->fetch(PDO::FETCH_ASSOC);
echo $sth;

I'm trying to insert data into the CLENTES table in the CNPJ field and this error is occurring:

( ! ) Catchable fatal error: Object of class PDOStatement could not be converted to string in C:\wamp\www\site\index.php on line 30
Call Stack
#   Time    Memory  Function    Location
1   0.0000  134952  {main}( )   ..\index.php:0

What can I do to fix this?

    
asked by anonymous 06.07.2015 / 16:55

4 answers

5

The problem is that you're trying to give echo $ sth ... Only $ sth is not string type. So the mistake.

Just delete the echo $sth; as the error some.

Edit: Try to do this:

$cnpj = "000001";
$db = new PDO(
    "mysql:host=host.com.br; dbname=databaseName",
    "usuario",
    "senha"
);
$db->query("INSERT INTO CLENTES (
    CNPJ
)
VALUES (
    ?
); ");
$result = db->query("Select * From CLENTES")->fetch(PDO::FETCH_ASSOC);
    
06.07.2015 / 16:59
1

Try something like this since you just want to sign up.

$cnpj = "000001";
$sth = $lokos->prepare("INSERT INTO CLENTES (CNPJ) VALUES (?)"); 
$sth->execute(array($cnpj)); 

Remembering that your $lokos variable should be the one that connects to the database, usually $conn something of the type is used.

    
06.07.2015 / 18:40
1

Your logic is wrong ...

$cnpj = "000001";
$sth = $lokos->prepare("INSERT INTO CLENTES (CNPJ) VALUES (?)"); 
$sth->bindParam(1, $cnpj, PDO::PARAM_STR);
$sth->execute();
// Até aqui está mais ou menos certo 

// O comando fetch serve para consultas, ou seja, SELECTs - ESTÁ ERRADO
$result = $sth->fetch(PDO::FETCH_ASSOC);
// Você não pode imprimir um objeto com echo
echo $sth;    

Do as follows:

$cnpj = "000001";
$sth = $lokos->prepare("INSERT INTO CLENTES (CNPJ) VALUES (:cnpj)"); 
$sth->bindParam(':cnpj', $cnpj, PDO::PARAM_STR);
$sth->execute();   
    
06.07.2015 / 20:11
0
  

Object of class PDOStatement could not be converted to string

This error is caused by the line echo $sth; , $sth is not a scalar variable, to print objects or arrays use the print_r () or var_dump () . p>

The insert does not normally return value, in this case remove the line

$result = $sth->fetch(PDO::FETCH_ASSOC);

To treat and discover the error in the query, add an if at run ()

if($sth->execute() === false){
   print_r($sth->errorInfo);
}
    
06.07.2015 / 17:02