Problem with Insert and PDO

1

I'm trying to make an insert with PDO. For this I use:

controller / com_clients.add.php

<?php
if($action == "new_client"){
    $search_cod_cliente = $pdo->prepare("SELECT MAX(cli_cod_cliente) AS cli_cod_cliente FROM clients"); 
    $search_cod_cliente->execute();

    while($result_cod_cliente = $search_cod_cliente->fetchObject()){
        $cli_cod_cliente = $result_cod_cliente->cli_cod_cliente + 1;
    }

    $conectar = new Con_Clients_Add;
    $conectar = $conectar->con_clients_add($cli_cod_cliente);
}
?>

classes / Con_Clients_Add.class.php

<?php
    class Con_Clients_Add{
        public function con_clients_add($cli_cod_cliente){
            try {
                $pdo = new PDO('mysql:host='.$host.';dbname='.$database, $login_db, $senha_db);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
            }

            $client_insert = $pdo->prepare("INSERT INTO clients(cli_cod_cliente) VALUES (:cli_cod_cliente)");
            $client_insert->bindParam(':cli_cod_cliente', $cli_cod_cliente, PDO::PARAM_STR);
            $client_insert->execute(); 
        }
    }
?>

But if you use the traditional method, it works:

$db = mysql_connect ($host, $login_db, $senha_db);
$basedados = mysql_select_db($database);

$insere_cliente = mysql_query("INSERT INTO clients(cli_cod_cliente) VALUES ('$cli_cod_cliente')");

Thanks for the strength. Hugs. Rafael

    
asked by anonymous 06.01.2017 / 18:40

1 answer

1

The problem seems to be that your con_clients_add method is being interpreted as a class constructor, then on the first call.

A method with the same class name in some circumstances is considered as constructor.

Ideally, you should set the constructor to __construct() or rename your method.

$conectar = new Con_Clients_Add; //primeira chamada
$conectar = $conectar->con_clients_add($cli_cod_cliente); segunda chamada

Simple example

class abc{
    public function abc(){
        echo 'sou o construtor<br>';
    }
}

$a = new abc();
$a->abc();

Output:

sou o construtor
sou o construtor
    
06.01.2017 / 18:51