With the popularity of NoSQL database management systems, the data storage of many software has turned to MongoDB database. It uses a dynamic schema to convert data into structured JSON document storage to improve application performance.
In this chapter tutorial, we learn to use PHP and MongoDB to realize simple user login function.
the
Before learning this tutorial, please ensure that the PHP mongo driver already exists. If you do not have it, please download it from the following address:
Windows:
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/
Linux and Mac
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
Connect to MongoDB
no authenticated connection
<?php
$mongo = new Mongo();
$db = $mongo->selectDB(“test”);
?>
verify connection
<?php
$mongo = new Mongo(“mongodb://{$username}:{$password}@{$host}”);
$db = $mongo->selectDB(“test”);
?>
By default, MongoDB has a “test” sample database. Or you can also create a new database:
$db = $mongo->Database_Name;
Inquire
PHP get database list
Mongo can also use the following command on the terminal to achieve the above query effect:
db.listDatabases
db.test.showCollections
create collection (table)
PHP statement to create a table
$db->createCollection(“people”, false);
False here means infinite size, if true, you must specify the maximum space of the table.
Mongo terminal command to create the table:
$db->createCollection(“people”, false);
insert record
PHP code to insert record
Mongo terminal command to insert records
b.people.insert({user:”user_name”,password:”password”});
update record
PHP code to update MongoDB
<?php
$update = array(“$set” => array(“user” => “[email protected]”));
$where = array(“password” => “password”);
$people->update($where,$update);
?>
Mongo terminal command to implement update
db.people.update({password:”password”},{$set :
{user:”[email protected]”}});
HTML form
Email:
Password:
Complete PHP code index.php
<?php
$succss = “”;
if(isset($_POST) and $_POST[‘submitForm’] == “Login” )
{
$usr_email = mysql_escape_string($_POST[‘usr_email’]);
$usr_password = mysql_escape_string($_POST[‘usr_password’]);
$error = array();
// Email Validation
if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL))
{
$error[] = “Empty or invalid email address”;
}
if(empty($usr_password)){
$error[] = “Enter your password”;
}
if(count($error) == 0){
$con = new Mongo();
if ($con){
// Select Database
$db = $con->test;
// Select Collection
$people = $db->people;
$qry = array(“user” => $usr_email,”password” => md5($usr_password));
$result = $people->findOne($qry);
if($result){
$success = “You are successfully loggedIn”;
// Rest of code up to you….
}
} else {
die(“Mongo DB not installed”);
}
}
}
?>
This article describes an example of PHP MongoDB implementing simple user login. I hope this article can bring inspiration to readers and help readers solve questions. Thank you for reading this article.