I am trying to fetch the content of inserted row, immediately after inserting it using php+mysql. Is there any way in php+mysql to immediately get the inserted row (all columns).
I am new to php+mysql.
Try this:
<?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);
?>
After inserting the row fetch the inserted row. below example uses php prepared statement method for insert into and fetch data from database table.
for databse connection you will have to create php codes.
database connection
$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();
Immediately after executing this you can query the same table and get the row. Like this--
$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();
If the data is inserted it is available for you to fetch.
You can get the latest inserted row id by the in built php Function mysql_insert_id();
$id = mysql_insert_id();
you an also get the latest row id by
$id = last_insert_id();
If the data is inserted into the successful return should be a new id