简体   繁体   English

用pdo在两个mysql表中插入一条记录

[英]Insert a record in two mysql tables with pdo

I've been trying to do this with TWO different queries, but only the first one works. 我一直在尝试使用两个不同的查询来执行此操作,但是只有第一个有效。 PDO is new for me that's why i'm a little confuse. PDO对我来说是新的,这就是为什么我有些困惑。

    <?php
include 'database.php';
$nombres=$_POST['tnombres'];
$apellidos=$_POST['tapellidos'];
$carrera=$_POST['tcarrera'];
$con->beginTransaction();

try{

        // insert query
        $query = "INSERT INTO alumno (nombres,apellidos) VALUES (:nombres,:apellidos)"`;`

        // prepare query for execution
        $stmt = $con->prepare($query);

        // bind the parameters
        $stmt->bindValue(':nombres',$nombres,PDO::PARAM_STR);
        $stmt->bindValue(':apellidos',$apellidos,PDO::PARAM_STR );
        $stmt->execute();
        $ultimo=$con->lastInsertId();

        $query = "INSERT INTO ficha (fechaingreso,carrera,alumno_id) VALUES (:fechaingreso,:carrera,:alumno_id)";
        $stmt = $con->prepare($query);

        $fecha=  date('d-m-Y');
        $stmt->bindValue(':fechaingreso',$fecha);
        $stmt->bindValue(':carrera',$carrera);
        $stmt->bindValue(':alumnoid',$ultimo);
        $stmt->execute();

        $con->commit(); 
        echo 'Datos insertados';
        echo '<p><a href=index.php>Inicio</a></p>';
        echo "<p>Numero de ultimo registro insertado: ",$ultimo;
    }

    // show error
    catch(PDOException $e){
        $con->rollback();
        echo $e->getMessage();
    }

Like i said before the first query works perfectly even the capture of the id from the last record inserted works but the second query don't do what it have to. 就像我说的那样,即使第一个查询完美地执行,甚至从插入的最后一条记录中捕获ID都可以,但是第二个查询却不执行它必须做的事情。 I have this message of error 我有此错误消息

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\wamp\www\escuela\crear.php on line 32

You have a typo in your script. 您的脚本中有错字。 In your INSERT you are using alumno_id but later you try to bind the value via alumnoid . 在您的INSERT您使用alumno_id但是稍后您尝试通过alumnoid绑定值。

$query = "INSERT INTO ficha (fechaingreso,carrera,alumno_id) VALUES (:fechaingreso,:carrera,:alumno_id)";

The underscore is missing - alumnoid is not the same as alumno_id . 缺少下划线- alumnoidalumno_id

$stmt->bindValue(':alumnoid',$ultimo);

As @FirstOne allready mentioned it: The solution is to add or remove the _ underscore from one of the both variables. 正如@FirstOne早已提到的那样:解决方案是在两个变量之一中添加或删除_下划线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM