我试图在使用php + mysql插入后立即获取插入行的内容。 在php + mysql中是否有任何方法可以立即获取插入的行(所有列)。
我是php + mysql的新手。
答案 0 :(得分:0)
试试这个:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
答案 1 :(得分:0)
插入行后获取插入的行。 下面的例子使用php prepared语句方法插入和从数据库表中获取数据。
对于数据库连接,您必须创建php代码。
数据库连接
$servername = "your server name";
$username = "your username";
$password = "your password";
$db = "your database name";
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: try again after some time ");
}
$insert_stmt = $conn->prepare("INSERT INTO log (username, email, password)
VALUES (?, ?, ?)"));
$insert_stmt->bind_param('sss', $username, $email, $password);
$insert_stmt->execute();
执行此操作后,您可以立即查询同一个表并获取该行。像这样 -
$prep_stmt = "SELECT * FROM log WHERE username = ? LIMIT 1";
$stmt = $conn->prepare($prep_stmt);
$stmt->bind_param('s', the username you just inserted);
$stmt->execute();
$stmt->bind_result($the variable names in which you want to bind the
results separated by commas);
$stmt->fetch();
如果插入了数据,则可以获取。
答案 2 :(得分:0)
您可以通过内置的php函数mysql_insert_id();
$id = mysql_insert_id();
你也可以通过
获得最新的行ID$id = last_insert_id();
答案 3 :(得分:0)
如果数据被插入成功返回应该是一个新的id