1
I have an inheritance in my work and I’m struggling to make it work.
Example of the Tables
CREATE TABLE IF NOT EXISTS pessoa (
idpessoa INT NOT NULL AUTO_INCREMENT,
tipopessoa VARCHAR(45) NOT NULL,
PRIMARY KEY (idpessoa)
);
CREATE TABLE IF NOT EXISTS juridica (
idjuridica INT NOT NULL AUTO_INCREMENT,
cnpj VARCHAR(25) NOT NULL,
inscrestad VARCHAR(45) NOT NULL,
razaosocial VARCHAR(150) NOT NULL,
nomefantasia VARCHAR(150) NOT NULL,
pessoa_idpessoa INT NOT NULL ,
PRIMARY KEY (idjuridica),
FOREIGN KEY (pessoa_idpessoa) REFERENCES pessoa (idpessoa)
);
Well, this is a part of the inheritance that I have, I’m trying to register a legal person, but first I have to register Pessoa. I’m using PHP (learning now) and the code is the following for inserting a legal person.
Connection to the bank:
function abrirBanco(){
$connection = new mysqli("localhost","root","","apsbd1");
if($connection->connect_error){
die("Conexão com o banco falhou: " . $connection->connect_error);
}
return $connection;
}
INSERT of Legal Person:
function inserirPJuridica(){
$banco = abrirBanco();
//Insere uma Pessoa;
$sql = "INSERT INTO pessoa (tipopessoa) VALUES ('Juridica')";
$banco->query($sql);
//Seleciona o ID da Pessoa;
$sql = "SELECT idpessoa FROM pessoa ORDER BY idpessoa DESC LIMIT 1";
$res_idpessoa = $banco->query($sql);
//Insere a Conexão entre Pessoa e Jurídica;
$sql = "INSERT INTO juridica (cnpj, inscrestad, razaosocial, nomefantasia, pessoa_idpessoa) VALUES ('{$_POST["cnpj"]}', '{$_POST["inscrestad"]}', '{$_POST["razaosocial"]}', '{$_POST["nomefantasia"]}', '$res_idpessoa'";
$banco->query($sql);
The Person I can insert into the bank, but when I insert Legal it gives a mistake
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\apsbd1\inc\funcoes.php on line 302
Line 302 is the $res_idpessoa line = $database->query($sql);
Probably the query is not a string that can be used in an INSERT, as I do to then insert the person table’s idperson into the person’s legal table?
The PK Person Insert as FK in the Legal table worked, however, the same is not happening with the table "contact" that has the fields (person_idpessoa and contact_idcontato), I have to rewrite the idpessoa SELECT, or I can take advantage for the next INSERT?
– Gian Carlo Mdr
You can pass the $data['idpessoa'] returned from this query to be used in the contact, as I understood it would be the next query to be performed, if that’s it.
– Solange