0

I am trying to update an array in mongoDB code is executing without an error but the document is not being updated.

here is my code:

<?php
include 'connection.php';
session_start ();
$username = $_SESSION ['username'];
$collection = $database->selectCollection ( $username );

$books = $collection->find ( array (
        '_id' => new MongoId ( $_POST ['id'] ) 
) );
$book = $books->getNext ();
$imgid = $book ['imgid'];
$id = $book['_id'];

if (isset ( $_POST ['formsubmit'] )) {

    $gridFS = $database->getGridFS ();

    // if (isset ( $_FILES ['pic'] ))
    // $imgid = $gridFS->storeUpload ( 'pic', array (
    // "username" => $username
    // ) );

    $collection->update ( array (
            "_id" => new mongoId ( $id ) 
    ), array (
            '$set' => array (
                    'bookname' => $_POST ['bookname'],
                    'authname' => $_POST ['authname'],
                    'pubname' => $_POST ['pubname'],
                    'imgid' => $imgid,
                    'cost' => $_POST ['cost'] 
            ) 
    ) );

    echo '<h3>File Updated Successfully</h3>';

}
$mongo->close ();
?>
<html>
<head>
<title>Online Book Exchange::Exchange old/Used books</title>
<link rel="icon" href="images/favicon.ico">
<link href="style/own.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="container_box">

        <div class="navbar">
            <p>
                <a href="session.php">Dash Board</a> &nbsp;|&nbsp; <a
                    href="logout.php"
                    onClick="return confirm('Are you sure you want to Logout?')">Logout</a>
            </p>
        </div>
        <br> <br>
        <div class="motofont">
            <h3>
                <img src="images/LogoShortMedium.png" alt="Online book store"
                    width="162" height="39" />&nbsp;&nbsp;&nbsp; Edit Book
            </h3>
            <hr>
        </div>
        <br> <br>
        <div id="errorBox"></div>
        <form name="form" method="POST" enctype="multipart/form-data"
            action="editbook.php">
            <table width="60%" cellspacing="2" cellpadding="5" align="center">
                <tr>
                    <td>
                        <div class="reg_font">Book Name :</div>
                    </td>
                    <td><input type="text" name="bookname" id="bookname" class="txt"
                        value="<?php echo $book['bookname']; ?>" /></td>
                </tr>
                <tr>
                    <td>
                        <div class="reg_font">Author Name:</div>
                    </td>
                    <td><input type="text" name="authname" id="authname" class="txt"
                        value="<?php echo $book['authname']; ?>" /></td>
                </tr>
                <tr>
                    <td>
                        <div class="reg_font">Publication Name:</div>
                    </td>
                    <td><input type="text" name="pubname" id="pubname" class="txt"
                        value="<?php echo $book['pubname']; ?>" /></td>
                </tr>
                <tr>
                    <td>
                        <div class="reg_font">Cost</div>
                    </td>
                    <td><input type="text" name="cost" id="cost" class="txt"
                        value="<?php echo $book['cost']; ?>" /> <input type="hidden"
                        name="id" id="id" value="<?php $id?>" /></td>
                </tr>
                <tr>
                    <td><div class="reg_font">Upload an Image:</div></td>
                    <td><input type="file" name="pic" id="pic" class="btn_2" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center" valign="middle"><button
                            type="submit" value="Register" name="formsubmit" id="formsubmit" class="btn">Edit</button></td>
                </tr>
            </table>
        </form>
        <hr>
    </div>
</body>
</html>

i have taken 'id' from a different file by POST method and searched for required document in this file. then i quoted update query. but its not working

and also how do i check if image is selected in the form? i want to replace existing image if new image is uploaded.

thanks in advance

1 Answer 1

2

i have taken 'id' from a different file by POST method and searched for required document in this file. then i quoted update query. but its not working

If you're selecting a single document from the collection, you should consider using MongoCollection::findOne(), which conveniently returns the first matching document (as an associative array) or null if no document was found. This is more efficient than creating a Cursor with find() and calling getNext().

At a glance, I would assume that the form is not functioning because you're not properly echoing the identifier value. To quote your example:

<input type="hidden" name="id" id="id" value="<?php $id?>" />

<?php $id?> is essentially a NOP. You probably mean to print $id as a string instead.

As a side observation, I see no reason to $set the imgid field in your update query. Between the find() query and the update, this value never changes. Additionally, $id is previously assigned to $book['_id'], which should already be a MongoId object. In that case, there is no reason to construct a new MongoId object in the update criteria. You should be able to use $id as-is (since it's a MongoId).

and also how do i check if image is selected in the form? i want to replace existing image if new image is uploaded.

In addition to storing the username with the GridFS file, I would suggest adding the book identifier so that you can easily determine the related book from the file document if need be. The commented code you have looks correct. What may be missing is deleting the original file, which would be the $book['imgid'] (if anything). I would suggest deferring this cleanup step until after the new GridFS insertion and update succeeds.


On a separate note: you should not be calling MongoClient::close() at the end of your script. In fact, the documentation strongly encourages against it, as it defeats the driver's ability to use persistent connections.

Also, since you appear to be using usernames as collection names, I would suggest you review MongoDB's collection naming restrictions to ensure that you do not inadvertently attempt to use invalid names. This looks like an attempt at multi-tenancy, which is usually done at the database level instead of separate collections. Unless you really need to segregate the data, I would suggest storing it in a single collection to start. That will require you to store the username, or better yet a user identifier, in each book document; however, a single collection makes it much easier to keep track of indexes and avoids the possible conflict(s) in using usernames as collection names.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.