Capture ID with php and mysql

0

How to capture ID of a table with prepared statement in php and mysql to assign this Id that was captured and add it through a insert as foreign key of the following table. here the code:

<?php

//Tabla Cliente
$nom = $_POST["nombre"];
$ape = $_POST["apellido"];
$mail = $_POST["correo"];
$obs = $_POST["observacion"];
$con = $_POST["contrasena"];
$rut = $_POST["rut"];
$fono = $_POST["num_telefono"];

// Tabla Dirección
$calle = $_POST["calle"];
$num = $_POST["num_calle"];
$com = $_POST["comuna"];
$reg = $_POST["region"];



require('otraconexion.php');


    //Consulta Tabla Cliente

    $sql = "INSERT INTO cliente VALUES (NULL,?,?,?,?,?,?,?)";
    $resultado = mysqli_prepare($conexion, $sql);


$ok = mysqli_stmt_bind_param($resultado,"ssssisi",$nom,$ape,$mail,$obs,$con,$rut,$fono);
$ok = mysqli_stmt_execute($resultado);
$fk = $sql->mysqli_insert_id();

//Consulta Tabla Direccion

$sql2 = "INSERT INTO direccion VALUES (NULL,?,?,?,?,?)";
$resultado2 = mysqli_prepare($conexion, $sql2);

if(!$resultado2){
echo "Error al insertar.".mysqli_error($conexion);
}

$ok = mysqli_stmt_bind_param($resultado2,"sissi",$calle,$num,$com,$reg,$fk);
$ok = mysqli_stmt_execute($resultado2);



if($ok==false){

    echo"Error,";
}else{

    header("Location: ../Acceso/Indexp.php");

}

mysqli_stmt_close($resultado);


?>
    
asked by Luis Estay 20.07.2018 в 02:40
source

1 answer

-1

Here is the solution to capture the Id for tables related to prepared queries, in this case do it with PDO in php.

The connection

<?php

try{
        $handler = new PDO('mysql:host=127.0.0.1;dbname=test','root','');
        $handler->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Sorry , DataBase Problem';
die();
}

if($handler == true)
{

}

    ?>

Form and Queries:

 <?php
require('otraconexion.php');
//Table Cliente
$nom = $_POST["nombre"];
$ape = $_POST["apellido"];
$mail = $_POST["correo"];
$obs = $_POST["observacion"];
$con = $_POST["contrasena"];
$rut = $_POST["rut"];
$fono = $_POST["num_telefono"];

// Table Dirección
$calle = $_POST["calle"];
$num = $_POST["num_calle"];
$com = $_POST["comuna"];
$reg = $_POST["region"];

//Query Table Cliente
$sql = "INSERT INTO cliente VALUES (NULL,?,?,?,?,?,?,?)";
$query = $handler->prepare($sql);
$query->execute(array($nom, $ape, $mail, $obs,$con, $rut, $fono));
$fk= $handler->lastInsertId();
echo $fk;

//Query Table Direccion
$sql2 = "INSERT INTO direccion VALUES (NULL,?,?,?,?,".$fk.")";
$query = $handler->prepare($sql2);
$query->execute(array($calle, $num, $com, $reg));




?>
    
answered by 20.07.2018 в 06:44