0

I'm using PHP 5.6.16 accessing MongoDB 3.2 via the MongoDB driver for PHP (php_mongo-1.6.14-5.6-ts-vc11-x64), and I've already been able to create a few pages.

I need to create a page that lists the employees registered in MongoDB from a text entered by the user, for example, the first name (the name field in MongoDB stores the full name).

Using the mongoshell, I can execute this query in the following command

db.employee.find("name":/Rogerio/)

If I try to pass the full name as a parameter, logically the search works (see full PHP code below).

<?php
    $m = new MongoClient("mongodb://localhost:27017");
    $collection = $m->mydb->employees;

    echo "<form action='' method=post>";
    echo "<input type='text' name='name'>";
    echo "<input type=submit name=search value=Search>";
    echo "</form>";

    if (isset($_POST['search'])){
    $name = $_POST['name'];
    $employees = $collection->find(array('name' => $name));

    echo "<table border=0 rules=rows width=600>";
    foreach ($employees as $emp){
        echo "<tr>";
        echo "<td>{$emp['nome']}</td>";
        echo "</tr>";
    }
    echo "</table>";
}
?>

To be able to search for a part of the name, I tried to use the following code to set $name:

$name = "/" . $_POST['name'] . "/";

but it did not work.

How to pass this kind of parameter to the PHP driver?

1 Answer 1

1

You can try with

$employees = $collection->find(array('name' => array("$regex" => $name)));

With this option you will search using regular expressions, it´s more or less equivalent to "LIKE" statements in MySQL.

You can use this in mongo shell as follows:

db.employee.find({"name":{"$regex": "Rogerio"}})

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

2 Comments

It worked! Thank you! I just needed to correct a small detail: '$regex' (not double quotation marks)
Yes! the correct one is: $employees = $collection->find(array('name' => array('$regex' => $name)));

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.