Take a value from another field other than id

Asked

Viewed 51 times

0

I have the following tables:

1 - Assignments with the following fields: Id, Request, Collaborator and Date Assignment.

2 - States with the following fields: id, State and State.

Numpedido is equal to Idestado.

Now I want you to insert me in the Attribution table to enter me in the State table, but I want you to fetch me the value of the Numrequest of the first table automatically and insert me in the State table in the State field.

If I were to pick up the id I would use the following code:

$sql = "INSERT INTO AtribuicaoLuvas (NumPedido,Colaborador,DataAtribuicao)
VALUES ('$pedido','$colaborador','$data')";

if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
}

$sql1 = "INSERT INTO EstadoLuvas (`IdEstado`,`Estado`) 
VALUES ('$last_id','$estado')"; 

if ($conn->query($sql1) === TRUE);

but in this case as I do?

  • Can you explain better? I don’t quite understand what you want

  • 1

    In the first insert the value of the NumPedido is = $pedido, thence in the second Insert make the value of the IdEstado = $pedido

  • Leo Caracciolo, thanks for the tip. I solved my problem

1 answer

-1

Whereas you are using PDO.

First let’s "prepare()" the query, replacing the user-sent values with ? (this also solves the SQL Injection problem).

In "execute()" you send an array with the value of each field.

If the error code == 00000 then everything went right.

<?php 
$sql = "INSERT INTO AtribuicaoLuvas (NumPedido, Colaborador, DataAtribuicao) VALUES (?, ?, ?)";

$consulta = $pdo->prepare($sql);
$consulta->execute(array($pedido, $colaborador, $data);

if ($consulta->errorCode() == '00000') {
  $last_id = $pdo->lastInsertId();

  $sql = "INSERT INTO EstadoLuvas (`IdEstado`,`Estado`) VALUES (?, ?)"; 

  $consulta = $pdo->prepare($sql);
  $consulta->execute(array($last_id, $estado);
}
?>

Browser other questions tagged

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