delete document with php

47 views
Skip to first unread message

Anis Mrad

unread,
Aug 2, 2015, 3:36:40 PM8/2/15
to mongodb-user

Hello,


I want to delete a document with PHP. My database is Mongodb.

This is my database article : The collection is articles


{ "_id" : ObjectId("55be575271dd7ec905b7acda"), "title" : "test", "content" : "Test", "user" : "Paul", "saved_at" : ISODate("2015-08-02T17:49:45.776Z") }

So for example if I want to delete an article. I have tried this code :


ListArticle.php

try {
           $connection = new MongoClient();
           $database   = $connection->selectDB('blog');
           $collection = $database->selectCollection('articles');
         } catch(MongoConnectionException $e) {
           die("Failed to connect to database ".$e->getMessage());
}
            $query=array();
            $cursor=$collection->find($query);
            foreach ($cursor as $doc) {
                echo " Title : ".$doc['title']." "."by ".$doc['user'];                  
                ?>
                <form method="POST" action="script.php" onsubmit="return confirm('do you want to delete this article ?')">
                <br/>
                <?php 
                echo "<input type='submit' value='Delete'>";
                $v=$doc["content"];
                echo "<input type='hidden' name='content' value=$v>";
                echo "</form><br/>";
}


script.php

try
            {
            $connection = new MongoClient();
            $database = $connection->selectDB('blog');
            }

        Catch(MongoException $e)
            {
            die("Failed to connect to database " . $e->getMessage());
            }

  $collection = $database->articles;



    $query=array("content"=>$_POST["content"]);
    $collection->remove($query);

    echo "<p>Success !</p>";


    ?>


When I click delete article it does not remove

Thanks with the help


guido hornig

unread,
Aug 2, 2015, 4:39:46 PM8/2/15
to mongod...@googlegroups.com

Anis Mrad

unread,
Aug 3, 2015, 2:13:10 PM8/3/15
to mongodb-user
?

Le dimanche 2 août 2015 22:39:46 UTC+2, guido hornig a écrit :

Doug Reese

unread,
Aug 3, 2015, 9:57:53 PM8/3/15
to mongodb-user
Usually you would want to delete based on document _id.  The hidden form field would look something like:

$id = $doc["_id"];
echo "<input type='hidden' name='id' value=$id>";

Then in script.php

$query = array('_id' => $_POST['id']);
$collection->remove($query);
Reply all
Reply to author
Forward
0 new messages