Create an residence book with PHP

Lorna Jane Mitchell and Steve Francia explain how to use PHP and MongoDB to make an residence book that’s stretchable adequate to keep opposite kinds of contacts in order

This essay initial seemed in emanate 228 of .net repository – a world’s best-selling repository for web designers and developers.

MongoDB is a request database designed for opening and scale while remaining easy for developers to use. The tenure request database is mostly misunderstood – it’s not referring to PDF and DOC files, nonetheless a request database in this box means storing arrays. MongoDB is mostly grouped with other non-relational databases, called NoSQ.

MongoDB provides dual facilities that can be deliberate groundbreaking. First, it works with local denunciation types, so a database works for we rather than we carrying to heed to it. It feels so healthy to simply save arrays or objects that you’ll fast forget we are regulating a database. Second, a schema is totally stretchable definition that any record can enclose opposite fields. When operative on an residence book application, it struck us that this stretchable structure would be fanciful for traffic with all a several kinds of contacts!

I have residence book entries for people who have 3 email addresses, nonetheless no postal address. Then there’s Auntie Flo, who has dual postal addresses given she migrates with a intent – nonetheless she doesn’t have a mobile phone. This essay goes by how to pattern a schema to use with MongoDB, and how we built a PHP focus on tip of it.

People and phone numbers

We can emanate people in a residence book and associate opposite kinds of information with opposite people, afterwards store this in MongoDB regulating PHP. As a elementary initial instance let’s see an array of information combined in PHP and how to save to MongoDB:

  1. $mum = array(“name” => array(“first” => ”mum”),
  2. “phone” => array(
  3. array(“number” => ”01234567890″, ”label” => ”work”),
  4. array(“number” => ”07890123456″, ”label” => ”mobile”))
  5. );
  6. $mongo = new Mongo();
  7. $db = $mongo->addresses;
  8. $db->people->save($mum);

First we emanate a array of data, that should be sincerely informed even if PHP isn’t your local language. Then we emanate a tie to a MongoDB database by formulating a new Mongo object.

The PHP libraries for doing MongoDB are strong and approachable, and have unequivocally glorious documentation; by default a new Mongo intent will simply bond to a MongoDB server on localhost nonetheless we can pass additional parameters if we indispensable to configure this for another aim database.

Databases and collections

Accessing a addresses skill tells PHP to use that database on a MongoDB server, and we afterwards save a information to a people collection. Collections in MongoDB are like tables in a relational database, a place where we keep identical annals together.

Neither a addresses database nor a people collection needs to be combined in advance; MongoDB is designed to hoop ever-changing and elaborating schemas so there is no need to set anything in stone. Do take caring though, given if we mistype (or my favourite, mis-plural) a list name, there will be no blunder shown!

We can record into MongoDB directly and take a demeanour during what we have in a database during this indicate as seen in a picture below.

Create an residence book with PHP

Here we can see a phone numbers displayed for a initial entrance in a residence book

Does a approach a phone numbers are stored seem bizarre to you? We could of march have finished this instead:

  1. $mum = array(“name” => array(“first” => ”mum”),
  2. “phone” => array(
  3. “work” => ”01234567890″,
  4. “mobile” => ”07890123456″)
  5. );

These equipment of information are usually a array of phone numbers, they’re homogeneous to one another so we usually store them all as “number” as shown in a initial example, and insert labels to them. It’s tantalizing to use this latter instance given it does seem a bit simpler; however, in this case, we need to bear in mind how we will entrance a data.

If we store phone numbers as graphic fields, we will be looking for a phone series for a person, though meaningful either it’s a mobile or a work phone. The structure we have selected creates it easy to demeanour adult a chairman by phone number, and provides a ability to supplement some-more fact if a need ever arises. So we have selected to store a list of phone numbers for any person, with some information trustworthy to contend what kind of a series it is.

Here we can see a information for a hypothetical residence book entry, trimming from candid phone numbers to minute geolocation information

Here we can see a information for a hypothetical residence book entry, trimming from candid phone numbers to minute geolocation information

Storing addresses

Address books were creatively dictated for addresses, so let’s take a demeanour during how we competence go about formatting these for a integrate of opposite locations. For example, a entrance for Bob Smith in a MongoDB looks like a one in a picture above.

Bob has houses on both sides of a pool (one in a US, one in Europe), and we can see that we’ve usually used a fields suitable to how a addresses should be formatted in any nation given MongoDB enables us to do so. This is one of a best things about MongoDB; we can usually supplement whatever fields are applicable to any record and nest a information as deeply as creates clarity in any case. If we saw my genuine residence book with people’s phone numbers, addresses, and birthdays (not to discuss their children’s birth dates), all scribbled opposite space dictated for fax numbers, we would know since this resolution appeals so much!

Data entry

Up to now, we’ve been hard-coding arrays of data, so let’s do something a bit nicer to emanate a form we can use to supplement people and several entries for them. We’ve been regulating PHP to routine forms given perpetually nonetheless it’s a sincerely critical partial of a system, so let’s take a demeanour during a picture shown on a left (‘Mum’s a word’). This is driven by a elementary form estimate system; a form itself is a simple template and it submits to a book that simply saves a new record:

  1. if($_SERVER['REQUEST_METHOD'] == ”POST”) {
  2. $person = array();
  3. // sanitise
  4. if(isset($_POST['first_name'])) {
  5. $person['name']['first'] = filter_input(INPUT_POST, ”first_name”,
  6. FILTER_SANITIZE_STRING);
  7. }
  8. if(isset($_POST['last_name'])) {
  9. $person['name']['last'] = filter_input(INPUT_POST, ”last_name”, FILTER_
  10. SANITIZE_STRING);
  11. }
  12. $mongo = new Mongo();
  13. $db = $mongo->addresses;
  14. $person['created'] = new MongoDate();
  15. $db->people->save($person);
  16. header(“Location: list.php”);
  17. } else {
  18. // uncover template
  19. include(“input.html”);
  20. }

Find your friends

Putting information into a complement is all unequivocally well, nonetheless we’ll still need to be means to find people by any one of a series of criteria. In sequence to demeanour during opposite ways we competence use to find people and their compared data, we’ll use MongoDB directly from a authority line to query a information and see a formula that are returned.

The MongoDB website is well-designed apparatus charity useful support and a good operation of examples
The MongoDB website is well-designed apparatus charity useful support and a good operation of examples

Let’s start with a simplest box and simply demeanour for people whose final name is Smith. The find() process in MongoDB takes an array of criteria either we are regulating it from a authority line or from PHP itself. Here, we’re looking for a final margin inside a name field, and given this is JavaScript we can usually use a dot to use a nested skill value as a criteria.

  1. db.people.find( {‘name.last’ : ’smith’ } );

This retrieves, in their entirety, a annals we have for everybody with a name.last margin set to smith in a database. In accurately a same way, we can lift fields from within addresses that compare a sold value and are nested inside a record.

As good as relating specific values, MongoDB can accept queries that use a unchanging countenance to compare fragments of a value; for instance try this:

  1. db.people.find( { ”address.street” : /61st/ } );

This will lapse all addresses with 61st somewhere in a address. travel element. It’s a customary (preg) unchanging countenance doing so all we already know about unchanging expressions will request here too – creation for some unequivocally absolute hunt capabilities.

We can hunt on mixed criteria by provision mixed criteria into a array when we search, so by doing something like this:

  1. db.people.find({“name.last” : ”smith”, ”name.first”: ”bob”});

When we have mixed nested records, however, we need something a bit some-more specific to contend that we’re looking for an residence in a sold state and city. If we simply combined criteria for address.state and address.city, we would get people relating who had mixed addresses, where one matched on state and one matched on city. To get around this, we use a $elemMatch user to contend that within one address, mixed elements contingency compare – for instance we could demeanour for people with NY state addresses that are indeed in New York City by doing:

  1. db.people.find( { address : { $elemMatch : { state : ’NY’, city : ’new york’ }}})

There are many other ways to collect out accurately a information that we need from MongoDB, and luckily a support is finished unequivocally good with transparent examples – we can find it all over during mongodb.org.

Our residence book’s form estimate complement enables us to emanate contacts and classify them by a series of opposite criteria

Our residence book’s form estimate complement enables us to emanate contacts and classify them by a series of opposite criteria

Geographical locations

If we were looking closely, we might have speckled co-ordinates fields in a screenshot of Bob Smith’s information on page 99. These paint embodiment and longitude, and MongoDB has some neat facilities for traffic with it. Within any collection, we can supplement one index to make essential values for geographical data. For this application, we used this command:

  1. db.people.ensureIndex( { ’address.coordinates’ : ’2d’ });

The 2d tells MongoDB that this is geographical latitude/longitude information and it should therefore be dual numbers, any in a operation of +/-180. Looking during a information we posted above, we can see that a UK residence gives us a mark in poetic Cumbria (see picture below).

MongoDB has some good facilities for traffic with your contacts’ geolocation information such as embodiment and longitude details

MongoDB has some good facilities for traffic with your contacts’ geolocation information such as embodiment and longitude details

MongoDB knows that this is geographic data, so we can start to make use of geo-specific facilities when we work with it. For instance we’re means to use a $near user in sequence to fetch entries circuitously to a given embodiment or longitude point:

  1. db.people.find( { ’address.coordinates’ : { $near : [52,-3] } } );

This earnings annals for all a addresses in a database, systematic by their stretch from a indicate we gave.

We can urge on this hunt by looking for addresses within a given stretch (distance is a bit of a downy judgment here given we’re operative in embodiment and longitude – a earth is not flat, and unequivocally a maths would make an glorious essay of a own) to find entries that are nearby. We can use a $maxDistance operator, like this:

  1. db.people.find( { ’address.coordinates’ : { $near : [52,-3], $maxDistance: 50 } } );

Once again, this finds us Bob’s record; we could equally have used a limit() duty to lapse a set series of annals if we were regulating a bigger dataset, that would be useful if we were looking for a nearest 5 friends to visit, for example.

The Mongo prolongation for PHP unequivocally usually enables us to entrance all of MongoDB’s functionality in a lucid way, so to use a same techniques in a focus ends adult looking utterly similar. The query above looks like this when we supplement it into a application:

  1. $mongo = new Mongo();
  2. $db = $mongo->addresses;
  3. $criteria = array(‘address.coordinates’ => array(‘$near’ => array(53, -3),
  4. ‘$maxDistance’ => 50));
  5. $list = $db->people->find($criteria);
  6. print_r(iterator_to_array($list));

We will have a MongoCursor to a collection in $list, that we can iterate over to get a formula returned by a queries. For tiny information sets, we can also use a iterator_to_array() duty to usually give an array structure that we can use as we wish.

MongoDB and nested data

Hopefully this essay has supposing we with an bargain of how stretchable information can be intensely accessible to work with regulating MongoDB. We equivocate separating out annals usually to recombine them any time we collect a data, nonetheless we can still hunt deeply within those annals in sequence to find things by several criteria.

The support for geospatial acid in MongoDB goes distant over what is shown here, nonetheless all being good it has given we a ambience of a kinds of things we can grasp with these tools.

VN:F [1.9.22_1171]
Rating: 10.0/10 (1 opinion cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
Create an residence book with PHP, 10.0 out of 10 formed on 1 rating

Leave a Comment

Comments are moderated. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!


− four = 3