Peter Pik
Peter Pik

Reputation: 11193

insert data and return it as json

I have below code, which is inserting data into a mysql database. However when the data is added i want to return this row as json. Is it possible to get this from the current insert query or would i have to make a new select query and if yes, then how do i retrieve the added id from this insert query?

$stmt = $db->prepare("INSERT INTO camps (title, body, longitude, latitude, image) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('ssdds', $title, $body, $longitude, $latitude, $link);
$stmt->execute();

Upvotes: 0

Views: 48

Answers (1)

Fabricator
Fabricator

Reputation: 12772

The inserted id is available from mysqli::$insert_id. You either need to build the row manually from the insert data, or run a select:

$id = $db->insert_id;
$result = $db->query("select * from camps where id = $id");
$json = json_encode($result->fetch_assoc());

Upvotes: 1

Related Questions