0% found this document useful (0 votes)
5 views1 page

DB PHP

Uploaded by

ajayrgavali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

DB PHP

Uploaded by

ajayrgavali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

<?

php
require 'C:\xampp\vendor\autoload.php'; // Composer autoload (mongodb library)

// 1. Connect to MongoDB
$client = new MongoDB\Client("mongodb://localhost:27017");

// Select Database & Collection


$database = $client->testdb;
$collection = $database->person;

// ----------------------------------------------------
// INSERT (Create)
echo "<h2>Insert Document</h2>";
$insertResult = $collection->insertOne([
"name" => "Ajay",
"age" => 20,
"gender" => "m"
]);
echo "Inserted with Object ID: " . $insertResult->getInsertedId() . "<br>";

// ----------------------------------------------------
// READ (Retrieve)
echo "<h2>Retrieve Documents</h2>";
$users = $collection->find();
foreach ($users as $user) {
echo $user["_id"] . " | " . $user["name"] . " | " . $user["age"] . " | " .
$user["gender"] . "<br>";
}

// ----------------------------------------------------
// UPDATE
echo "<h2>Update Document</h2>";
$updateResult = $collection->updateOne(
["name" => "Ajay"], // Condition
['$set' => ["age" => 21]] // Update
);
echo $updateResult->getModifiedCount() . " document(s) updated.<br>";

// Show updated data


$updatedUser = $collection->findOne(["name" => "Ajay"]);
echo "Updated: " . $updatedUser["name"] . " - Age: " . $updatedUser["age"] .
"<br>";

// ----------------------------------------------------
// DELETE
echo "<h2>Delete Document</h2>";
$deleteResult = $collection->deleteOne(["name" => "Ajay"]);
echo $deleteResult->getDeletedCount() . " document(s) deleted.<br>";

// Final check
echo "<h2>All Documents After Deletion</h2>";
$allUsers = $collection->find();
foreach ($allUsers as $user) {
echo $user["_id"] . " | " . $user["name"] . " | " . $user["age"] . " | " .
$user["gender"] . "<br>";
}
?>

You might also like