douzheng5717 2018-07-20 02:30
浏览 58

如何使用php和mysql从表中捕获ID

my question is:

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

Basically I have two tables 'Cliente' and 'Direccion' so I want the ID (pk) from Cliente and put that ID (after the first query) in the ID(fk) from Direccion for both tables are related .

When i try to run the form in my page this message error appears:

Fatal error: Uncaught Error: Call to a member function mysqli_insert_id() on string in
C:\xampp\htdocs\compra\compraegistro\FormRegistro_reg.php:31 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\compra\compraegistro\FormRegistro_reg.php on line 31

here's the code:

<?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"];



require('otraconexion.php');


    //Query Table 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();

//Query Table Dirección

$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);


?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥170 如图所示配置eNSP
    • ¥20 docker里部署springboot项目,访问不到扬声器
    • ¥15 netty整合springboot之后自动重连失效
    • ¥15 悬赏!微信开发者工具报错,求帮改
    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥15 键盘指令混乱情况下的启动盘系统重装