Select user id and insert in another table


I have a problem that I can not solve.

Ahem: table 1 and table 2, in table 1 I have already registered the user and this one is already with the session started with id1. In table 2 I'm trying to insert the id1 and other information of another form.

To explain myself better I am trying to select a primary key and insert this in another table as a foreign key, since the user is already logged in.

I already look for information in the php manual but I can not make the INSERT_ID() OR LAST_INSERT_ID work always presents me with an error.


$cpf = $_POST['cpf'];
$numero =$_POST['numero'];
$nomebanco = $_POST['nomebanco'];
$agencia =$_POST['agencia'];

$idUsuario = $_SESSION['id_usuario'];
$selecionaid = "SELECT * FROM usuarios WHERE id='$idUsuario'";
$result = $mysqli->query($selecionaid);

$sql = "INSERT INTO tbbancarios (cpf, numero, nomebanco, agencia, conta) VALUES ('#cpf', '$numero', '$nomebanco', '$agencia', '$conta', '$result')";
    $resultado = $mysqli->query($sql);
    if ($resultado) {
      echo "New record created successfully";
} else {
      echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
asked by everson 03.01.2019 в 12:33

1 answer


In the question several syntax faults are seen, although some may be at the time of formulating this.

When you make INSERT INTO tbbancarios , you specify 5 fields ( (cpf, numero, nomebanco, agencia, conta) ) but then you pass 6 values ( '#cpf', '$numero', '$nomebanco', '$agencia', '$conta', '$result') ). Also #cpf is badly written since it should be $cpf and if the field is numeric type it should go without quotes.

On the other hand, in the $result of the first select you collect all the user data (you do not specify what they are) and you put them all in the second query.

If you want to get only the id to put it in the second table because you do SELECT * ?

And if that is what you want, the select does not return the same id that your variable $idUsuario has?

In this case you need to do this:

$sql = "INSERT INTO tbbancarios (cpf, numero, nomebanco, agencia, conta, idusuario) VALUES ('$cpf', '$numero', '$nomebanco', '$agencia', '$conta', '$idUsuario')";
$resultado = $mysqli->query($sql);
answered by 03.01.2019 в 12:52