PHP& MySQL获取最后一个插入ID [英] PHP & mySQL obtaining last insert ID

查看:76
本文介绍了PHP& MySQL获取最后一个插入ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这笔php/mysql交易非常陌生,我很难特别地弄清楚这种情况.

I'm quite new to this php/mysql deal and I'm having a hard time figuring out this situation particularily.

我有两个表,其中一个是"dog"表,另一个是"date"表.为了在狗"表中插入一条记录,我必须首先在表"日期中插入一个日期,并从该日期获取自动增量ID.

I have two tables, one of them is "dog" table and the other one is the "date" table. In order to insert a record in the "dog" table I MUST first insert a date in the "table" date and get the autoincrement id from that date.

问题是我尝试阅读几篇有关如何从刚刚插入记录的表中获取最后一个插入ID的文章,但我似乎无法使其正常工作.

Problem is that I've tried reading several posts on how to get the last insert id from a table you just inserted a record on and I can't seem to make it work.

$sql1="INSERT INTO FECHAS (fecha) VALUES (NOW())";
mysql_query($sql1);
echo $sql1;

$sql3="SELECT LAST_INSERT_ID()";
mysql_query($sql3);
echo $sql3;



  $sql2="INSERT INTO PERRO (nombre_perro,FECHAS_id_fecha) VALUES ('$nombre_perro_var', '$last_id')";
echo $sql2;
if (!$mysqli->query($sql2)) {
    echo 'Error: ', $mysqli->error;
}
$result2 = mysql_query($sql2); 

请原谅这段代码,我是新手,正在学习.

Please forgive this code, I'm new and learning.

谢谢!

推荐答案

使用mysqli代替mysql_

与mysqli连接:

$connection = mysqli_connect($hostname, $username, $password, $database_name);

插入表格:

mysqli_query($connection, $sql);

获取最后插入的ID:

$id = mysqli_insert_id($connection);

这篇关于PHP& MySQL获取最后一个插入ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆